From be6863e9a16bcc3a09d87c50981e69292795a512 Mon Sep 17 00:00:00 2001 From: kvalls <95490470+kvalls@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:11:06 +0100 Subject: [PATCH 001/189] feat(ghidra): support native PE DLLs on Windows --- .github/workflows/real-ghidra-windows.yml | 20 +++ AGENTS.md | 2 +- docs/installation.md | 2 +- docs/managed-code-analysis.md | 5 +- docs/provider-evaluation.md | 9 +- docs/roadmap.md | 2 +- docs/windows-ghidra-p0.md | 15 +- scripts/create-ghidra-windows-fixture.mjs | 155 +++++++++++++-------- scripts/verify-packaged-ghidra-windows.mjs | 114 ++++++++++++--- scripts/verify-real-ghidra-windows.mjs | 27 +++- src/ghidra/GhidraAnalysisProfile.ts | 6 + src/ghidra/GhidraProvider.behavior.test.ts | 84 ++++++----- src/ghidra/GhidraProvider.ts | 9 +- src/ghidra/GhidraProviderCapabilities.ts | 2 +- 14 files changed, 316 insertions(+), 136 deletions(-) diff --git a/.github/workflows/real-ghidra-windows.yml b/.github/workflows/real-ghidra-windows.yml index 42dc38fa4..d6de7469f 100644 --- a/.github/workflows/real-ghidra-windows.yml +++ b/.github/workflows/real-ghidra-windows.yml @@ -64,6 +64,14 @@ jobs: env: REA_ANALYSIS_PROVIDER: ghidra run: npm run verify:ghidra:windows -- --x86 | Tee-Object -FilePath windows-ghidra-x86-proof.log + - name: Verify native x64 DLL Windows Ghidra operations + env: + REA_ANALYSIS_PROVIDER: ghidra + run: npm run verify:ghidra:windows -- --dll | Tee-Object -FilePath windows-ghidra-dll-proof.log + - name: Verify native x86 DLL Windows Ghidra operations + env: + REA_ANALYSIS_PROVIDER: ghidra + run: npm run verify:ghidra:windows -- --x86 --dll | Tee-Object -FilePath windows-ghidra-x86-dll-proof.log - name: Verify ordinary-user CLI and MCP operations env: REA_ANALYSIS_PROVIDER: ghidra @@ -72,6 +80,14 @@ jobs: env: REA_ANALYSIS_PROVIDER: ghidra run: npm run verify:ghidra:windows:package -- --x86 | Tee-Object -FilePath windows-ghidra-x86-package-proof.log + - name: Verify ordinary-user x64 DLL CLI and MCP operations + env: + REA_ANALYSIS_PROVIDER: ghidra + run: npm run verify:ghidra:windows:package -- --dll | Tee-Object -FilePath windows-ghidra-dll-package-proof.log + - name: Verify ordinary-user x86 DLL CLI and MCP operations + env: + REA_ANALYSIS_PROVIDER: ghidra + run: npm run verify:ghidra:windows:package -- --x86 --dll | Tee-Object -FilePath windows-ghidra-x86-dll-package-proof.log - uses: actions/upload-artifact@v4 if: always() with: @@ -81,4 +97,8 @@ jobs: windows-ghidra-package-proof.log windows-ghidra-x86-proof.log windows-ghidra-x86-package-proof.log + windows-ghidra-dll-proof.log + windows-ghidra-x86-dll-proof.log + windows-ghidra-dll-package-proof.log + windows-ghidra-x86-dll-package-proof.log retention-days: 30 diff --git a/AGENTS.md b/AGENTS.md index 1acb82552..01ecf3d91 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Product Direction -REA exposes reverse-engineering tools through a CLI and MCP server. Hopper, the bring-your-own Ghidra adapter, and the bring-your-own IDA MCP adapter are operation-capable deep binary-analysis providers. Ghidra is supported on Linux x64/arm64 and macOS x64/arm64 with matching native decompiler tools, and has an experimental Windows x64 P0 boundary for approved native x86 and x86-64 PE applications; on Linux and macOS it supplies inventory, function analysis, and atomic function annotation edits in an ephemeral database, without modifying executable bytes or controlling a GUI. Windows P0 has no mutation authority. IDA adapts upstream legacy attached GUI and modern headless database-supervisor profiles for live read-only analysis; initial real verification covers Windows, and an attached GUI database is never saved or closed. Keep provider-specific code out of the domain and application layers. +REA exposes reverse-engineering tools through a CLI and MCP server. Hopper, the bring-your-own Ghidra adapter, and the bring-your-own IDA MCP adapter are operation-capable deep binary-analysis providers. Ghidra is supported on Linux x64/arm64 and macOS x64/arm64 with matching native decompiler tools, and has an experimental Windows x64 P0 boundary for approved native x86 and x86-64 PE applications and DLLs; on Linux and macOS it supplies inventory, function analysis, and atomic function annotation edits in an ephemeral database, without modifying executable bytes or controlling a GUI. Windows P0 has no mutation authority. IDA adapts upstream legacy attached GUI and modern headless database-supervisor profiles for live read-only analysis; initial real verification covers Windows, and an attached GUI database is never saved or closed. Keep provider-specific code out of the domain and application layers. Prioritize: diff --git a/docs/installation.md b/docs/installation.md index a0be32920..dfa3bc84b 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -452,7 +452,7 @@ entry comments atomically and returns refreshed analysis. These session metadata edits leave executable bytes unchanged and are discarded on close. GUI controls require Hopper; Windows P0 remains read-only. -Windows P0 admits native x86 and x86-64 PE applications on fixed local NTFS volumes. +Windows P0 admits native x86 and x86-64 PE applications and DLLs on fixed local NTFS volumes. The npm package bundles native Job Object ownership, protected private runtime DACLs, and handle-based path admission; no separate addon installation is needed. See the [Windows Ghidra P0 guide](windows-ghidra-p0.md) for verified scope and diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.md index 92bc23060..bb87a7a63 100644 --- a/docs/managed-code-analysis.md +++ b/docs/managed-code-analysis.md @@ -125,8 +125,9 @@ The upstream analyzer currently gates its own analysis to x86-64. NativeAOT's broader platform matrix does not establish REA coverage: PE/COFF, ELF, Mach-O, shared libraries, target architectures, and runtime metadata versions each need their own provider verification. REA's experimental Windows Ghidra boundary is -limited to admitted native x86 and x86-64 PE applications, so it does not currently -establish coverage for PE DLLs. Mobile NativeAOT targets should remain +limited to admitted native x86 and x86-64 PE applications and DLLs for static +analysis. This does not establish Windows NativeAOT metadata-recovery coverage. +Mobile NativeAOT targets should remain experimental until REA has a matching provider and package-level verification. For REA's native analysis, preserve the same artifact path and digest used by diff --git a/docs/provider-evaluation.md b/docs/provider-evaluation.md index 8aa655e52..a18303a92 100644 --- a/docs/provider-evaluation.md +++ b/docs/provider-evaluation.md @@ -18,7 +18,7 @@ comments atomically, verifies readback, and returns refreshed function analysis. Changes live only in the session database and leave executable bytes unchanged. Ghidra does not expose GUI controls; Windows P0 remains read-only. -Windows x64 P0 supports native x86 and x86-64 PE applications on local NTFS with +Windows x64 P0 supports native x86 and x86-64 PE applications and DLLs on local NTFS with bundled Job Object ownership, protected runtime DACLs, and handle-based path admission. Real ordinary-user verification covers all 25 read-only operations through the packaged CLI and MCP, target integrity, and cleanup. This remains @@ -62,7 +62,7 @@ maximum, when the release leaves those at the 12.1 defaults). Otherwise doctor probes `java`/`javac` or `java.exe`/`javac.exe` from `PATH`. Supported Linux and macOS hosts accept compatible ELF, PE, and Mach-O executable targets. Host admission and target compatibility are separate checks. Windows x64 P0 admits only native, -non-managed, non-DLL x86 and x86-64 PE applications on fixed local NTFS, with the packaged +non-managed x86 and x86-64 PE applications and DLLs on fixed local NTFS, with the packaged native authority available before launch. The launcher creates one ephemeral runtime root with project, @@ -136,8 +136,9 @@ Mach-O target coverage. It requires `clang`, LLD, and `lld-link`; set these tools before compilation. Keeping this matrix separate lets Linux host/provider acceptance run with only the host compiler. -`npm run verify:ghidra:windows` and its `-- --x86` variant check the source-owned native x86 and x86-64 PE -fixture, all 25 read-only operations, target/snapshot/import SHA-256 linkage, +`npm run verify:ghidra:windows` and its `-- --x86` variant check source-owned native x86 and x86-64 PE +applications. Adding `-- --dll` or `-- --x86 --dll` selects entry-point-free DLLs +with exported caller/callee functions. These lanes check all 25 read-only operations, target/snapshot/import SHA-256 linkage, and project, endpoint, process, and runtime cleanup. The independent native lane checks DACLs, handle admission, cancellation, and Job Object lifecycle. `npm run verify:ghidra:windows:package` packs and installs REA into an isolated diff --git a/docs/roadmap.md b/docs/roadmap.md index b4ac0ba54..077efa632 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -87,7 +87,7 @@ and exact commands. Experimental Windows x64 P0 now supplies bundled Job Object ownership, protected runtime DACLs, and handle-based admission for native x86 and x86-64 PE -applications on local NTFS. Real ordinary-user CLI/MCP verification covers +applications and DLLs on local NTFS. Real ordinary-user CLI/MCP verification covers all 25 read-only operations and cleanup. The [Windows P0 guide](windows-ghidra-p0.md) describes this boundary and unverified broader coverage. diff --git a/docs/windows-ghidra-p0.md b/docs/windows-ghidra-p0.md index ec54f5908..5f50d832c 100644 --- a/docs/windows-ghidra-p0.md +++ b/docs/windows-ghidra-p0.md @@ -17,7 +17,7 @@ additional permission flag or degraded mode is required. - Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+; - an operator-installed Ghidra 12.1.x distribution (verified with 12.1.4); - a 64-bit full JDK inside that installation's declared Java range (JDK 21 or newer, with no maximum, for current 12.1 releases); -- an explicit native, non-managed, non-DLL x86 or x86-64 PE application; and +- an explicit native, non-managed x86 or x86-64 PE application or DLL; and - the 25 read-only Ghidra inventory, memory, and function-analysis operations. Loaded memory reads and file offsets preserve Ghidra's observed source mappings. @@ -38,6 +38,13 @@ REA selects its packaged bridge scripts by explicit path. Same-named files or directories in the caller's working directory do not select a different script or require users to clean that directory before analysis. +Native DLL analysis preserves the PE shared-library role in the analysis profile. +REA imports an immutable copy for static analysis; it does not load the library +into the analyst process or execute its entry routine. The source-owned DLL +fixtures have no entry routine or imports and expose two exported functions. +The same native snapshot, path-admission and cleanup requirements apply to EXEs +and DLLs. + ## Configuration ```powershell @@ -100,7 +107,7 @@ and artifact SHA-256 before loading the package-owned addon. Native failure reasons remain distinct from a valid installation and an unsupported target. PE header classification and SHA-256 come from the same open file. The Windows -provider admits native x86 and x86-64 PE applications and rejects unsupported roles, +provider admits native x86 and x86-64 PE applications and DLLs and rejects unsupported roles, architectures, managed images, and malformed headers. The original selected source coordinate is preserved for native admission. @@ -159,7 +166,11 @@ artifact and manifest. npm run verify:windows-native npm run verify:ghidra:windows npm run verify:ghidra:windows -- --x86 +npm run verify:ghidra:windows -- --dll +npm run verify:ghidra:windows -- --x86 --dll npm run verify:ghidra:windows:package -- --x86 +npm run verify:ghidra:windows:package -- --dll +npm run verify:ghidra:windows:package -- --x86 --dll npm run verify:ghidra:windows:package -- C:\fixtures\installed-rea C:\fixtures\sample.exe ``` diff --git a/scripts/create-ghidra-windows-fixture.mjs b/scripts/create-ghidra-windows-fixture.mjs index 6538ec57f..e610b4688 100644 --- a/scripts/create-ghidra-windows-fixture.mjs +++ b/scripts/create-ghidra-windows-fixture.mjs @@ -3,68 +3,103 @@ import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +// Source-owned static fixtures: no compiler, target loading or execution. for (const architecture of ["x86_64", "x86"]) { - const x86 = architecture === "x86"; - const output = resolve( - root, - "build", - "fixtures", - x86 ? "rea-ghidra-windows-x86.exe" : "rea-ghidra-windows.exe", - ); - const bytes = Buffer.alloc(1024); - const peOffset = 0x80; - const optionalHeader = peOffset + 24; - const optionalHeaderSize = x86 ? 0xe0 : 0xf0; - const sectionTable = optionalHeader + optionalHeaderSize; + for (const dll of [false, true]) { + const x86 = architecture === "x86"; + const output = resolve( + root, + "build", + "fixtures", + `rea-ghidra-windows${x86 ? "-x86" : ""}.${dll ? "dll" : "exe"}`, + ); + const bytes = Buffer.alloc(1024); + const peOffset = 0x80; + const optionalHeader = peOffset + 24; + const optionalHeaderSize = x86 ? 0xe0 : 0xf0; + const sectionTable = optionalHeader + optionalHeaderSize; + const directories = optionalHeader + (x86 ? 96 : 112); - bytes.write("MZ", 0, "ascii"); - bytes.writeUInt32LE(peOffset, 0x3c); - bytes.write("PE\0\0", peOffset, "binary"); - bytes.writeUInt16LE(x86 ? 0x14c : 0x8664, peOffset + 4); - bytes.writeUInt16LE(1, peOffset + 6); - bytes.writeUInt16LE(optionalHeaderSize, peOffset + 20); - bytes.writeUInt16LE(x86 ? 0x102 : 0x22, peOffset + 22); + bytes.write("MZ", 0, "ascii"); + bytes.writeUInt32LE(peOffset, 0x3c); + bytes.write("PE\0\0", peOffset, "binary"); + bytes.writeUInt16LE(x86 ? 0x14c : 0x8664, peOffset + 4); + bytes.writeUInt16LE(1, peOffset + 6); + bytes.writeUInt16LE(optionalHeaderSize, peOffset + 20); + bytes.writeUInt16LE( + (x86 ? 0x102 : 0x22) | (dll ? 0x2000 : 0), + peOffset + 22, + ); - bytes.writeUInt16LE(x86 ? 0x10b : 0x20b, optionalHeader); - bytes.writeUInt32LE(0x200, optionalHeader + 4); - bytes.writeUInt32LE(0x1000, optionalHeader + 16); - bytes.writeUInt32LE(0x1000, optionalHeader + 20); - if (x86) bytes.writeUInt32LE(0x400000, optionalHeader + 28); - else bytes.writeBigUInt64LE(0x1_4000_0000n, optionalHeader + 24); - bytes.writeUInt32LE(0x1000, optionalHeader + 32); - bytes.writeUInt32LE(0x200, optionalHeader + 36); - bytes.writeUInt16LE(6, optionalHeader + 40); - bytes.writeUInt16LE(6, optionalHeader + 48); - bytes.writeUInt32LE(0x2000, optionalHeader + 56); - bytes.writeUInt32LE(0x200, optionalHeader + 60); - bytes.writeUInt16LE(3, optionalHeader + 68); - bytes.writeUInt16LE(x86 ? 0x8140 : 0x8160, optionalHeader + 70); - if (x86) { - bytes.writeUInt32LE(0x10_0000, optionalHeader + 72); - bytes.writeUInt32LE(0x1000, optionalHeader + 76); - bytes.writeUInt32LE(0x10_0000, optionalHeader + 80); - bytes.writeUInt32LE(0x1000, optionalHeader + 84); - bytes.writeUInt32LE(16, optionalHeader + 92); - } else { - bytes.writeBigUInt64LE(0x10_0000n, optionalHeader + 72); - bytes.writeBigUInt64LE(0x1000n, optionalHeader + 80); - bytes.writeBigUInt64LE(0x10_0000n, optionalHeader + 88); - bytes.writeBigUInt64LE(0x1000n, optionalHeader + 96); - bytes.writeUInt32LE(16, optionalHeader + 108); + bytes.writeUInt16LE(x86 ? 0x10b : 0x20b, optionalHeader); + bytes.writeUInt32LE(0x200, optionalHeader + 4); + bytes.writeUInt32LE(dll ? 0 : 0x1000, optionalHeader + 16); + bytes.writeUInt32LE(0x1000, optionalHeader + 20); + if (x86) bytes.writeUInt32LE(0x400000, optionalHeader + 28); + else bytes.writeBigUInt64LE(0x1_4000_0000n, optionalHeader + 24); + bytes.writeUInt32LE(0x1000, optionalHeader + 32); + bytes.writeUInt32LE(0x200, optionalHeader + 36); + bytes.writeUInt16LE(6, optionalHeader + 40); + bytes.writeUInt16LE(6, optionalHeader + 48); + bytes.writeUInt32LE(0x2000, optionalHeader + 56); + bytes.writeUInt32LE(0x200, optionalHeader + 60); + bytes.writeUInt16LE(3, optionalHeader + 68); + bytes.writeUInt16LE(x86 ? 0x8140 : 0x8160, optionalHeader + 70); + if (x86) { + bytes.writeUInt32LE(0x10_0000, optionalHeader + 72); + bytes.writeUInt32LE(0x1000, optionalHeader + 76); + bytes.writeUInt32LE(0x10_0000, optionalHeader + 80); + bytes.writeUInt32LE(0x1000, optionalHeader + 84); + bytes.writeUInt32LE(16, optionalHeader + 92); + } else { + bytes.writeBigUInt64LE(0x10_0000n, optionalHeader + 72); + bytes.writeBigUInt64LE(0x1000n, optionalHeader + 80); + bytes.writeBigUInt64LE(0x10_0000n, optionalHeader + 88); + bytes.writeBigUInt64LE(0x1000n, optionalHeader + 96); + bytes.writeUInt32LE(16, optionalHeader + 108); + } + + bytes.write(".text", sectionTable, "ascii"); + bytes.writeUInt32LE(dll ? 0x180 : 0x16, sectionTable + 8); + bytes.writeUInt32LE(0x1000, sectionTable + 12); + bytes.writeUInt32LE(0x200, sectionTable + 16); + bytes.writeUInt32LE(0x200, sectionTable + 20); + bytes.writeUInt32LE(0x6000_0020, sectionTable + 36); + + // EXE entry returns zero. DLL caller adds one to the callee's 42. + bytes.set( + dll + ? [0xe8, 0x0b, 0, 0, 0, 0x83, 0xc0, 1, 0xc3] + : [0xe8, 0x0b, 0, 0, 0, 0x31, 0xc0, 0xc3], + 0x200, + ); + bytes.set([0xb8, 0x2a, 0, 0, 0, 0xc3], 0x210); + + if (dll) { + // Export both functions; an entry-point-free library is discovered by exports. + bytes.writeUInt32LE(0x1040, directories); + bytes.writeUInt32LE(0x130, directories + 4); + const exports = 0x240; + bytes.writeUInt32LE(0x1100, exports + 12); + bytes.writeUInt32LE(1, exports + 16); + bytes.writeUInt32LE(2, exports + 20); + bytes.writeUInt32LE(2, exports + 24); + bytes.writeUInt32LE(0x1080, exports + 28); + bytes.writeUInt32LE(0x1088, exports + 32); + bytes.writeUInt32LE(0x1090, exports + 36); + bytes.writeUInt32LE(0x1000, 0x280); + bytes.writeUInt32LE(0x1010, 0x284); + bytes.writeUInt32LE(0x1120, 0x288); + bytes.writeUInt32LE(0x1140, 0x28c); + bytes.writeUInt16LE(0, 0x290); + bytes.writeUInt16LE(1, 0x292); + bytes.write("rea-fixture.dll\0", 0x300, "binary"); + bytes.write("fixture_caller\0", 0x320, "binary"); + bytes.write("fixture_return42\0", 0x340, "binary"); + } + + await mkdir(dirname(output), { recursive: true }); + await writeFile(output, bytes); + if (!x86 && !dll) process.stdout.write(`${output}\n`); } - - bytes.write(".text", sectionTable, "ascii"); - bytes.writeUInt32LE(0x16, sectionTable + 8); - bytes.writeUInt32LE(0x1000, sectionTable + 12); - bytes.writeUInt32LE(0x200, sectionTable + 16); - bytes.writeUInt32LE(0x200, sectionTable + 20); - bytes.writeUInt32LE(0x6000_0020, sectionTable + 36); - - // entry calls the second function, returns zero; second returns 42. - bytes.set([0xe8, 0x0b, 0, 0, 0, 0x31, 0xc0, 0xc3], 0x200); - bytes.set([0xb8, 0x2a, 0, 0, 0, 0xc3], 0x210); - - await mkdir(dirname(output), { recursive: true }); - await writeFile(output, bytes); - if (!x86) process.stdout.write(`${output}\n`); } diff --git a/scripts/verify-packaged-ghidra-windows.mjs b/scripts/verify-packaged-ghidra-windows.mjs index 17d29c4ad..268d949d9 100644 --- a/scripts/verify-packaged-ghidra-windows.mjs +++ b/scripts/verify-packaged-ghidra-windows.mjs @@ -15,7 +15,7 @@ import { import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { promisify } from "node:util"; -import { pathToFileURL } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; @@ -24,10 +24,43 @@ if (process.platform !== "win32" || process.arch !== "x64") throw new Error( "Packaged Windows Ghidra acceptance requires a Windows x64 host.", ); -const workspace = await mkdtemp(join(tmpdir(), "rea-packaged-ghidra-")); const exec = promisify(execFile); -const x86Fixture = process.argv[2] === "--x86"; -const packageRootArgument = x86Fixture ? undefined : process.argv[2]; +const arguments_ = process.argv.slice(2); +// Windows locks the loaded package-owned addon until the verifier exits. +// Keep installation cleanup in a parent that never loads that addon. +if (arguments_[0] !== "--internal-workspace") { + const ownedWorkspace = await mkdtemp(join(tmpdir(), "rea-packaged-ghidra-")); + try { + const result = await exec( + process.execPath, + [ + fileURLToPath(import.meta.url), + "--internal-workspace", + ownedWorkspace, + ...arguments_, + ], + { timeout: 900_000, maxBuffer: 8 * 1024 * 1024 }, + ); + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + } catch (cause) { + if (typeof cause.stdout === "string") process.stdout.write(cause.stdout); + if (typeof cause.stderr === "string") process.stderr.write(cause.stderr); + throw cause; + } finally { + await rm(ownedWorkspace, { recursive: true, force: true }); + } + process.exit(0); +} +assert.ok(arguments_[1] !== undefined, "Missing verifier workspace."); +const workspace = resolve(arguments_[1]); +const fixtureArguments = arguments_.slice(2); +const x86Fixture = fixtureArguments.includes("--x86"); +const dllFixture = fixtureArguments.includes("--dll"); +const [packageRootArgument, targetArgument, reportArgument] = + fixtureArguments.filter( + (argument) => argument !== "--x86" && argument !== "--dll", + ); let packageRoot = resolve(packageRootArgument ?? "."); // The default lane verifies the npm artifact in an isolated prefix. Explicit // package roots support an already-installed artifact without a second install. @@ -75,17 +108,17 @@ if (packageRootArgument === undefined) { ); packageRoot = join(prefix, "node_modules", "rea-agents"); } catch (cause) { - await rm(workspace, { recursive: true, force: true }); - throw cause; + throw new Error("Packaged Windows verifier installation failed.", { + cause, + }); } } const target = resolve( - process.argv[3] ?? - (x86Fixture - ? "build/fixtures/rea-ghidra-windows-x86.exe" - : "build/fixtures/rea-ghidra-windows.exe"), + targetArgument ?? + `build/fixtures/rea-ghidra-windows${x86Fixture ? "-x86" : ""}.${dllFixture ? "dll" : "exe"}`, ); let TOOL_CONTRACTS, native, token, sha256; +let parsedTarget; try { ({ TOOL_CONTRACTS } = await import( pathToFileURL(join(packageRoot, "dist/contracts/toolContracts.js")) @@ -107,9 +140,25 @@ try { ); const digest = (bytes) => createHash("sha256").update(bytes).digest("hex"); sha256 = digest(await readFile(target)); + const { parseBinaryTarget } = await import( + pathToFileURL(join(packageRoot, "dist/application/BinaryTargetResolver.js")) + ); + parsedTarget = await parseBinaryTarget(target); + assert.equal(parsedTarget.ok, true); + assert.equal(parsedTarget.value.format, "pe"); + assert.equal(parsedTarget.value.managed, false); + if (targetArgument === undefined) { + assert.equal( + parsedTarget.value.architecture, + x86Fixture ? "x86" : "x86_64", + ); + assert.equal( + parsedTarget.value.executableRole, + dllFixture ? "shared-library" : "application", + ); + } } catch (cause) { - await rm(workspace, { recursive: true, force: true }); - throw cause; + throw new Error("Packaged Windows verifier prerequisites failed.", { cause }); } const digest = (bytes) => createHash("sha256").update(bytes).digest("hex"); const runtimeParent = join(workspace, "runtime with spaces"); @@ -145,6 +194,8 @@ const report = { architecture: "x64", nonAdmin: true, targetSha256: sha256, + targetArchitecture: parsedTarget.value.architecture, + targetRole: parsedTarget.value.executableRole, cli: {}, mcpOperations: [], nativeControls: "available", @@ -208,8 +259,8 @@ try { }); const call = async (name, arguments_) => { report.lastOperation = name; - if (process.argv[4] !== undefined) - await writeFile(process.argv[4], `${JSON.stringify(report)}\n`); + if (reportArgument !== undefined) + await writeFile(reportArgument, `${JSON.stringify(report)}\n`); const contract = TOOL_CONTRACTS.find((value) => value.name === name); assert.ok(contract !== undefined, `Missing canonical contract: ${name}`); const argumentsParsed = contract.inputSchema.parse(arguments_); @@ -230,6 +281,25 @@ try { await call("list_names", {}); const procedures = await call("list_procedures", {}); assert.ok(procedures.length > 0); + if (targetArgument === undefined) { + const calleeAddress = x86Fixture ? "0x401010" : "0x140001010"; + const calleeCode = await call("procedure_pseudo_code", { + procedure: calleeAddress, + }); + assert.match(calleeCode, /\b(?:42|0x2a)\b/iu); + if (dllFixture) { + const callerAddress = x86Fixture ? "0x401000" : "0x140001000"; + assert.ok( + ( + await call("procedure_callees", { procedure: callerAddress }) + ).includes(calleeAddress), + ); + assert.match( + await call("procedure_pseudo_code", { procedure: callerAddress }), + /\+\s*1\b/u, + ); + } + } assert.ok((await call("list_segments", {})).length > 0); await call("list_strings", {}); const procedure = @@ -296,6 +366,12 @@ try { "Packaged verification omitted an admitted operation.", ); const session = await call("binary_session", {}); + assert.equal( + session.analysis_provider_binding?.analysis_profile?.parameters + ?.executable_role, + parsedTarget.value.executableRole, + "MCP profile must preserve the selected PE role.", + ); assert.equal( session.analysis_provider_binding?.selection_source, "auto-single-candidate", @@ -327,8 +403,8 @@ try { report.callerScriptCollisionsPreserved = true; report.runtimeCleanup = true; report.ok = true; - if (process.argv[4] !== undefined) - await writeFile(process.argv[4], `${JSON.stringify(report)}\n`); + if (reportArgument !== undefined) + await writeFile(reportArgument, `${JSON.stringify(report)}\n`); process.stdout.write(`${JSON.stringify(report)}\n`); } catch (cause) { report.failure = { @@ -338,9 +414,7 @@ try { .replaceAll(target, "") .replaceAll(workspace, ""), }; - if (process.argv[4] !== undefined) - await writeFile(process.argv[4], `${JSON.stringify(report)}\n`); + if (reportArgument !== undefined) + await writeFile(reportArgument, `${JSON.stringify(report)}\n`); throw cause; -} finally { - await rm(workspace, { recursive: true, force: true }); } diff --git a/scripts/verify-real-ghidra-windows.mjs b/scripts/verify-real-ghidra-windows.mjs index 1c5b3b829..3332ea4e2 100644 --- a/scripts/verify-real-ghidra-windows.mjs +++ b/scripts/verify-real-ghidra-windows.mjs @@ -62,21 +62,21 @@ if ( ); const root = resolve(fileURLToPath(new URL("..", import.meta.url))); -const architecture = process.argv[2] === "--x86" ? "x86" : "x86_64"; +const architecture = process.argv.includes("--x86") ? "x86" : "x86_64"; +const dllFixture = process.argv.includes("--dll"); +const role = dllFixture ? "shared-library" : "application"; const targetPath = resolve( root, "build", "fixtures", - architecture === "x86" - ? "rea-ghidra-windows-x86.exe" - : "rea-ghidra-windows.exe", + `rea-ghidra-windows${architecture === "x86" ? "-x86" : ""}.${dllFixture ? "dll" : "exe"}`, ); const target = await parseBinaryTarget(targetPath); if ( !target.ok || target.value.format !== "pe" || target.value.architecture !== architecture || - target.value.executableRole !== "application" || + target.value.executableRole !== role || target.value.managed !== false ) throw new Error( @@ -89,6 +89,8 @@ const profile = await resolveGhidraAnalysisProfile( ); if (!profile.ok || profile.value.profile === null) throw new Error("Windows Ghidra profile could not be committed"); +if (profile.value.profile.parameters.executable_role !== role) + throw new Error("Windows Ghidra profile lost the observed PE role"); const client = new GhidraClient({ platform: installation.platform, @@ -162,6 +164,19 @@ try { throw new Error( "Windows fixture decompilation lost its known return value", ); + if (dllFixture) { + const callerAddress = architecture === "x86" ? "0x401000" : "0x140001000"; + const callees = await functionOperation("procedure_callees", { + procedure: callerAddress, + }); + if (!callees.includes(callee.address)) + throw new Error("DLL export caller lost its controlled call reference"); + const callerCode = await functionOperation("procedure_pseudo_code", { + procedure: callerAddress, + }); + if (typeof callerCode !== "string" || !/\+\s*1\b/u.test(callerCode)) + throw new Error("DLL export caller lost its addition of one"); + } await inventory("inspect_native_load_image", {}); const memory = await inventory("read_bytes", { @@ -254,7 +269,7 @@ try { limitations: [ "approved-non-sensitive-fixtures-only", "windows-x64-local-ntfs-only", - "native-x86-and-x86-64-pe-applications-only", + "native-x86-and-x86-64-pe-applications-and-dlls-only", "no-gui-or-mutation-authority", ], }; diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index 1af7469fa..eeb8646a4 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -34,6 +34,12 @@ export const resolveGhidraAnalysisProfile = ( profile: createAnalysisProfile(provider, { target_kind: target.kind, target_format: target.format, + ...(target.format === "pe" + ? { + executable_role: target.executableRole ?? null, + managed: target.managed ?? null, + } + : {}), architecture: target.architecture ?? null, available_architectures: [ ...(target.availableArchitectures ?? []), diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index 7bbbc8c89..88e1eb07f 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -270,7 +270,7 @@ describe("Ghidra platform support", () => { expect( ghidra.inspectTargetSupport({ ...nativeApplication, - executableRole: "shared-library", + executableRole: "non-executable", }), ).toMatchObject({ status: "unsupported", @@ -295,45 +295,59 @@ describe("Ghidra platform support", () => { code: "architecture_unsupported", }); }); - it("admits generated PE32 applications while rejecting unsupported x86 roles", async () => { +}); + +describe("Ghidra Windows PE fixture admission", () => { + it("admits generated PE32 and PE32+ DLLs and applications while preserving native-only Windows admission", async () => { const root = fileURLToPath(new URL("../../", import.meta.url)); await promisify(execFile)(process.execPath, [ join(root, "scripts/create-ghidra-windows-fixture.mjs"), ]); - const path = join(root, "build/fixtures/rea-ghidra-windows-x86.exe"); - const bytes = await readFile(path); - const metadata = parseExecutableHeader(bytes, "x64"); - expect(metadata).toMatchObject({ - ok: true, - value: { - format: "pe", - architecture: "x86", - executableRole: "application", - managed: false, - }, - }); - if (!metadata.ok) throw new Error(metadata.error); - if (metadata.value.format !== "pe") - throw new Error("Expected a PE fixture"); - const target: BinaryTarget = { - path, - sha256: createHash("sha256").update(bytes).digest("hex"), - kind: "executable", - ...metadata.value, - }; const ghidra = provider({ ...installationHost(), platform: "win32" }); - expect(ghidra.inspectTargetSupport(target).status).toBe("supported"); - for (const [candidate, code] of [ - [ - { ...target, executableRole: "shared-library" }, - "target_role_unsupported", - ], - [{ ...target, managed: true }, "managed_target_unsupported"], - ] as const) - expect(ghidra.inspectTargetSupport(candidate)).toMatchObject({ - status: "unsupported", - code, - }); + for (const architecture of ["x86", "x86_64"] as const) { + for (const dll of [false, true]) { + const path = join( + root, + "build/fixtures", + `rea-ghidra-windows${architecture === "x86" ? "-x86" : ""}.${dll ? "dll" : "exe"}`, + ); + const bytes = await readFile(path); + const metadata = parseExecutableHeader(bytes, "x64"); + const role = dll ? "shared-library" : "application"; + expect(metadata).toMatchObject({ + ok: true, + value: { + format: "pe", + architecture, + executableRole: role, + managed: false, + }, + }); + if (!metadata.ok) throw new Error(metadata.error); + if (metadata.value.format !== "pe") + throw new Error("Expected a PE fixture"); + const target: BinaryTarget = { + path, + sha256: createHash("sha256").update(bytes).digest("hex"), + kind: "executable", + ...metadata.value, + }; + expect(ghidra.inspectTargetSupport(target).status).toBe("supported"); + for (const [candidate, code] of [ + [ + { ...target, executableRole: "non-executable" }, + "target_role_unsupported", + ], + [{ ...target, managed: true }, "managed_target_unsupported"], + [{ ...target, architecture: "arm64" }, "architecture_unsupported"], + ] as const) { + expect(ghidra.inspectTargetSupport(candidate)).toMatchObject({ + status: "unsupported", + code, + }); + } + } + } }); }); diff --git a/src/ghidra/GhidraProvider.ts b/src/ghidra/GhidraProvider.ts index d657a156e..d782827d9 100644 --- a/src/ghidra/GhidraProvider.ts +++ b/src/ghidra/GhidraProvider.ts @@ -247,12 +247,15 @@ const inspectWindowsP0TargetSupport = ( reason: "Windows Ghidra P0 accepts x86 and x86-64 PE targets only.", diagnostics, }; - if (target.executableRole !== "application") + if ( + target.executableRole !== "application" && + target.executableRole !== "shared-library" + ) return { status: "unsupported", code: "target_role_unsupported", reason: - "Windows Ghidra P0 accepts PE applications, not DLL or non-executable images.", + "Windows Ghidra P0 accepts PE applications and DLLs, not non-executable or unclassified images.", diagnostics, }; if (target.managed !== false) @@ -260,7 +263,7 @@ const inspectWindowsP0TargetSupport = ( status: "unsupported", code: "managed_target_unsupported", reason: - "Windows Ghidra P0 accepts native PE applications; managed or unclassified PE targets are unsupported.", + "Windows Ghidra P0 accepts native PE applications and DLLs; managed or unclassified PE targets are unsupported.", diagnostics, }; return { diff --git a/src/ghidra/GhidraProviderCapabilities.ts b/src/ghidra/GhidraProviderCapabilities.ts index edbbb11c3..5b9a6ca8b 100644 --- a/src/ghidra/GhidraProviderCapabilities.ts +++ b/src/ghidra/GhidraProviderCapabilities.ts @@ -31,7 +31,7 @@ export const healthLimitations = Object.freeze([ /** Additional limitations applied to the experimental Windows x64 P0 boundary. */ export const windowsP0Limitations = Object.freeze([ - "Windows Ghidra P0 accepts approved native x86 and x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.", + "Windows Ghidra P0 accepts approved native x86 and x86-64 PE applications and DLLs; managed, hostile, sensitive, and mutable-path targets are unsupported.", "The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.", "Windows sessions require the matching packaged Windows x64 native addon, local NTFS targets and runtimes, and Windows 10 or later. Native handles enforce path admission, private DACLs, and Job Object ownership automatically.", ]); From 4b8e744d90579e353371649047215c4e4be7a5f6 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:59:09 +0800 Subject: [PATCH 002/189] docs: add README artwork and refine closing sections --- README.md | 28 ++++++++++++++-------------- docs/assets/rea-license.png | Bin 0 -> 5961 bytes docs/assets/rea-showcases.png | Bin 0 -> 49446 bytes 3 files changed, 14 insertions(+), 14 deletions(-) create mode 100644 docs/assets/rea-license.png create mode 100644 docs/assets/rea-showcases.png diff --git a/README.md b/README.md index 78f8d1b04..c8b64f36a 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,8 @@ for features added since the latest npm release. ## Showcases +[![Illustrations of the DX-Ball sound-pan, Notion clipboard-bridge, and TH04 bullet-ring showcases](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: reconstruct a sound-pan calculation Follow a sound call into its position-to-pan helper, inspect the instructions, @@ -303,20 +305,6 @@ For exact options, prerequisites and result contracts: Report vulnerabilities through [SECURITY.md](SECURITY.md). -## Contributing - -We'd love your help with REA! [Open an issue](https://github.com/morluto/rea/issues) to -report a bug or suggest a feature, or [send a pull request](https://github.com/morluto/rea/pulls) -to improve the code or docs. - -See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and checks, -[testing](docs/testing.md) for verification lanes, and the -[architecture map](docs/architecture.mermaid) for the project structure. - -## Project links - -[Website](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Security](SECURITY.md) - ## Star history 🎉 **30,000 GitHub stars — thank you!** @@ -337,6 +325,18 @@ REA provides tools for lawful reverse-engineering research, analysis, and recons REA is an open-source software project. We have not issued or endorsed any cryptocurrency or token. Tokens using the REA name are not affiliated with the project. +## Contributing + +We'd love your help with REA! [Open an issue](https://github.com/morluto/rea/issues) to +report a bug or suggest a feature, or [send a pull request](https://github.com/morluto/rea/pulls) +to improve the code or docs. + +See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and checks, +[testing](docs/testing.md) for verification lanes, and the +[architecture map](docs/architecture.mermaid) for the project structure. + ## License +[![Software license document with a check seal](docs/assets/rea-license.png)](LICENSE) + [MIT](LICENSE) diff --git a/docs/assets/rea-license.png b/docs/assets/rea-license.png new file mode 100644 index 0000000000000000000000000000000000000000..9870754e4e8db4862d67366f4432f02b36dac274 GIT binary patch literal 5961 zcmV-P7q;k$P)004Lh0{{R3LVO8b00048P)t-s_4W7m z_W1Yr`S8bs{7yCMYc)ASL7D(e8QC2D~Gkbl4 zet?F7frf*Gif3tUE-*HYj*>1hIGvuNpP-|nqNTL7xRR2VM@ddwU}%Yoj*pO(m6e%? zh>TleY-DS7+}+{W*xDs2GFM(`UuSZ`!o|J5!G3~>hl-H+`1iWHz77*0A0{(>e~9do zU9em%wnY_sJtIt5YuQ^N_*ez;WDudAp&lYD-r(cN&DP1$*UZw|ny0xLJZUFMbR|Y| zEKGGRPI+g2n!CczGg5djP_dzFij9zkxn!OOM2%OfT+yv5NkPLRY$Po_HCTgdfSyroj(3Zt^_|2~00001Z*opl0neg$ng9S5 zn@L1LRCwC0T!~u~$+oZRbX6yWEr21=0c1%K5u-qq<*9?S+->g7xLgG%<~ox>8FAsw z`~Sc1Rn@8GRCOm|zV9A1>1>@}pHpW)6+#H1j-sd#1Ib6|wL&Cs;c4}PBFYFC#MBW< zl0-h2NK(&Bf=5I=p*~B!sIkhzj~`5{5cZU(N`NA{xbUWC0q~5}-mD zbMb(Q_rmAo5s%^A3ZFulV1(vjLYM{!ZzfE=DDD{?t4Fa9kW&qi$H0_`67>{S@R;J6 z*a)mJ3nOqsrLLk5?@LnLxwpy93MA3(DY>?r_XLtlyLq=IWfa)_Wvj7CP$f+=sXJkIlLVTPHEbc^1Diy=(?*TM#$^euM4FD4F zGoG-exG7VYgrpn51AMVmE<$roV>w9d)ezt^T3<%Iu@Xh>;jy3b&Ky(w84XbJ&#pjg zVF;Bkxpz{+eS`rw0G7QvY$NR&L}KP{$$G>AAcv1I1JJ1mGkO7+M=d}`vhwf&dh9p& zA`ou|pk4h;>K`}eRPb4w8}UKL3 z_F}QVIXD$=uY-laGWcLMSd~pkfG}qr<2A^^Rj366RzQfdU@zVSXqj&=BwPa)DG!|s z@k}^ckAOYkq}FF70i-fgwF?CckRyN&Py%))=fd6Bi=zQHD3Qj-gc(XniDIn9X)I2m zfH;HfP81^r&jmPuJ!gts~kH)R5F{ zHWxP+%T;kLx0XwlK`TE_M5TaB$r!NN3M-6;(KsPhLL?(tYhCKw>MX2$twFPt@|GAYfhx9-)}R_|}^ZUODJ zTKkF?7SxS~EzmaC+fxeQjn&yoPH09VDN3FCaDy=RJw+@7e-e8Dm9rx_zP76&Datz;QUwdalGk~0wvqsWg**F{zIirtioA88mV zN!!CEz}CI$+VTH19>t@q;I;&~cKl$qmaa`Kl=9sg(Z&Ql!9f)mg6db54Myp&Gv=jt-f42*L?S`sO>)|sfo2jP^y zCWy3@sTLx394w9oI0*ood&kwa+Vt!)9pIi_ScCw=y?`auNGg&zDmZ*zjoKWT3)Zd@DSec)i@NwZw7 z-`EL0=86u+yG5$hqB*ISS>ymRtL~X|fRdaTCAl8JscQXpdA;3iD_UP&s@FG587&s4 zrm;&KWg$awFtPw`)E8TOl&@&=@J|73i(p|X-LzrP{iU=z@$`@cd5B6^kq1V8*QF&~ zR^FHn7zdbwBq@{*oBQM6es}!v`)hHqTuU=_W4lz;DIRc8*$WoNQ-Xy$TxH4t3a3oD zQH6Yf;^2oLe)!7|fBEa*{(c<}?yt8OHzA&JBwUIDr~_&UWOOncXA)Nq?|}r_nU{P+ zDv$s1qo9BO_}6Oze7eE{o}`f z3c4P^V(HOtv#~zs(fVdb08DV@$N@wQ|MENI#aZoSyYwy*bew+}>^|fN*AK ze3_2yTnX1zQ*qaUaOORSqZtKo;a~gf{~52rnYw~7d%7O}k_%o%6wYzf{l*01(UEq*$7ckJ#?W9we+=)uE{N0HNFL8X%X zKY&iM0CA*g;wb%#17!7a4VmKeG4!dfX{S}p%-CWwl+F6t#Er1Rb++LA##$&o))nJNJ_&A zl&4?;-f?TtR#mlfA}?lIFQ~>QqH9~rXMTsD%A}sbldAk?04g(MO$peUpFR3b-Te0R z3jc&?Ssx1;_1UzOLtfn2o3;Qe!cf2VDX`R%q^kp^2?4s4QKZEx zC1N2!l?ebB<@b|Jf7?ZB#1xM-2Zh{LN-tma&d$!e-JYViXK#CF>OlPU-YT~z9-Y29 z$>$)nc5G@KtVEER4Y#-lFbSJKp#GABKEQXcUXLQ_>Q+2}#X-d*523y z2-^b~sWtf9v)_i3^n}m7HF)Pb09}<_n>Zc8vK)k_k|bUYIH+Bn(^z|J9|3s)x32+^ zIcAw&j++z;0V3BT06y8n989#o3oRZzvr?%@FKF>VxOEMH-YkQYHg_QwB|(EyXc+($ z9F)<_h6ecO4D}!m(jb!H z79ffRjUH1o)S_$DQpCTgU|~g-(N|WA9t{VWrzFr2l=%nCn-X!B#MqT2Gk_!2iXni& z!F*RY93V0?cBo615~5(XE(ajXY4^J%o7yVBQ<4`iZ@vV&Y3cp@K`g8+?61q}RuTd< zwT@u;j}EetlFzYzr>DrO%CEGzDFIeWAO3yu?%l=3g*3<)#xnQ(o{eqoR4R|3E~Ha; zOJ0N978gWDqT+f+Mv`nZtL_A2#Gh6y7(3XMzPKn|-TB*IK)+*v#lqaw_{8L-Y{HLE zEsjlW&%~(4Z+NI;{TL0Pk#LeD0M4XH<&uR862kyxPSTJ7r7!Nv^!KC8J$3eZe(D2^ zR=@33JJo7O(ERk>orPynUhu693!?=*KIH@S;4w81X4>`gvcTENh}v;5NtR!{c>Y|L z6rLLrM=wk$TR9nEiRn#g|WC`)Mbw`2Y#__f9jY)f1X^gFKFntARjO4YguX@w3PO%i#y96KD!KI8Wu`j23CxYQFl`Zi_Dg{ zOu&jcI5HDMn`KAM2>%a^p%pRYX+c&L+1u0jNgXEpN#%<$Ag&}i~P{!suA zXByR`e&@0WL9F6p@9TG+etLJgnCTtI)U$JRn2~`VeBQcrc2MUeL;P-OyVmb_(u*(W zXXg&!)t62uO~;r0q0PkaDN3=1gA*Bms?X?H4)K@^`5U7ElG6VCQF?iC-aGFad~aW! zUG=_Prk$w-8*3fPQ#S_5^n@P6Ssb1tl<$sFq+`d~48XAPK3CJ*+fOsIrLim2n9dz#-tfAa`lhZO;TiEi1#o%&-c;J}f9eW+ z=jU3!A4<19_Kn6B`CXJ@^$tCusSn}5h;Q~;d6w_9;AXHrAR;6~ON4AMe?V55Eif{`$L+w$$g33ZN?sh*L+IIpG`_%qy!qsAwD+ z11#imkApoYV|xHlu<%vyMN;{YB)`6S-976nZSJQUph+efI>%v*1jl-MC$JsUFGtwPA>$&dquoehY`ZbfJ~X%tqKeQK4Ce)+w3uK3rx`c&6}y(@y1!+s#H({gdOMFcNATuY$Jr+FOgllbrS-mO1U(+(iKF zl%Fq~oSS>O29CjWoI~+AmzHm^)kGIRTz#-!FT?cZ-j*eC*lO+VwOVQ-v(;*Uvnc=` zT?Pr&)#+Ce;!IT{7b%eZqM8ZBbS?^sslRJLb{7jCAC;1f*V3gmGg|A7*ed#dL(yDw zvnusO`jW2HW}xmD5pC7V%l;M_PsrNd7(vGr@i5%hKzM-$0NbtOaycDI_3HH8{mJy` z=;-rR*96o;p}!vW)3w#jiqlyZ6ef*5v{8iHKNstcnLotBJ%ESbY;7$F-sBBVFUfi8 zCH+cma=p1)U8~nGKYh7U3>5!Aed^cy^HW8dt<7Y%r`bA|-r0vn&Vwl%%52~$0Je8` zTZ?PuTR^vO-xfFG4`@w3aeGbNmDg6=8ym-xm+9r@=POB{E`@m0>T0tRs4I)2m=cz0 zRqMiy-q=T@nCAk7@fGlmrGxFA)?RCC*N{>WeYCr4RYt1H!v6L~xxCgtO4FmylKM;i ze!YCFc{c+PCbn2M2tc!2XmTdIb;Wc*)rYnlyX|IRRt)XJ?Jj7wQ0DE;T3swVSeN~! z`LwycoSA=PFsr3Q`!ERP8Gtai8Ulo{L&bWzHaaxePals7MlP(cPA#Rf?9mao6Vub} z?aUOW@?kX2gjY6(kvXXbs4*&T$IjfictIc(zN`RKrD`{=q{xwWekUiSG_$iKOybVw z(d}DeS&Fr~))*Vx8LQ;C9w~ATUaOkwOxbx3X16Q}Gvkf5Qf7Vn$Z{%7!0qm}v^C!o zX1#ec$qdaCJJ%nw5LTrw1Dd)a%kEc=@h&CR4!=IlK9X{7fq!Y;eEQ7JE1`XFwyPS4 z!i{aA)z&r9=7}IYl>E$Z0}ttC^U|{gyH#T6u;e?Cf!zo_F$0^|%uZ~U@rMMBt~h|n z^#GbT7F~hWTMs1IzUuRiGds)>Y0<-sYFJdn6KY&-LA)kDx7o`LR%dpB8d>GU(J^-! zCe3U?&1`lZ`1;`7c*J{cggU59j_Ul(0%St~jvSdFByTEr$o{nv-A=!lINK7GN|!x2t>r1Mw_aF2F*8 zdcmQaqGv=mcrsmgLUN^>H+aFqp9&zvcW172U_=!BEJ0+nl@Fc~;M@$=>g(l%3|!UB z8!ibJ0zrHu0b_HvtbkGRG9VhnUXY5A1nEnXGnnp`){!9##+&h$XRmLlFG=I$X5XKl zaLQU3)MkL-IU&fc1cT`V?G=UX!h@Kd1bf=u5Jw!3ZXCMpI&#YpCul&_xpcj7D8W5k zW?G{*+D!&e*=I&3m7k}hJDXNUJdT4+Yk1Qy{BR3XEJC#|83}(!BySPtm_Nf+ToKKSuNYyOl?TdgwKEC!5*vheG|n4!V40~4KQ<-d z3@@sPj*PEtmn8U!A~cZBY=^=H{2XV^xxd>%a(?JRox<#?Qa3*P*nkTr@S7~01o)tV zXxd~v^Ghr?ss%F<2eX)--2n3NT rG0Lcy*m%F|Vt!9W17xl=WDx#8XUVq`1d+T800000NkvXXu0mjf$vHN@ literal 0 HcmV?d00001 diff --git a/docs/assets/rea-showcases.png b/docs/assets/rea-showcases.png new file mode 100644 index 0000000000000000000000000000000000000000..b637ebb074c6d4d6a466f0075dd4c5b2736f22f1 GIT binary patch literal 49446 zcmWieWmME%7sdZGL#NW+A&qni(%m6a4&AAA4N6EzcZYO$!_Y`5-7$1`OZYzTS@+95 z-|jl=?zPwN>~IY=d29?a3;+PI6%}N(0006901zq~>E9of5w`}@BS z508Hzo*w@`JwE<-{;TJwzmI?atA~e&o4ecF`@5@~>+9Q_o7?-di}Ta-vy+qKm6a7M zE87qHAN7qa3yVs(wzn}bu(7c5P|>iEP%yw?h>P=={r&yWun00r22wIgJUqfzxcE4) z3Hb$t+uJ*4X6Nt;$lh{tDeD-^$STUJ>WN7yGBUCLh)Eb38SU)qX=-lm>+5gt9Z5+| zFD@;wsH!V3uPi7i%*)NIs%@yRZ*ceUfp_(so?Q$M{bJ$ZWq&I~LC3nXwxMNYX=vqY zVD4z;@Wt5X^XQ)$Ref_kQ+pi~TOYr#j&9zl=&wA##a~>U{=K`=c8aq0j!P@77Z#H# zYZ@RBu_lxGd~tRWmr?8$^;6o&mrc`$S=p0Y{qyA#AlBD$nf30kPQ;aTFbG&Vgk;hy zdjCE?lCkish`vq#qvH49JV4HFYC51l`JU+j00R_dBz3%&W;?^B2^5?5jgvlpO#7%w z`hFAKLX!)2DuG3C2(-|btP)j~aCjNFoh+`cWM@0CW!yCfl0JrW@M6~Nb=i>RmGJWf zxT<9~PTKILk6R%~Ov?$0{?)&3Jg}K1le`Et6oCAeXqKo`7g`+ua5gUA;KcLq;5AlAt z7ZybWA4r-3)RtUxO*qhJ_SDM&HUESU7%mC85+;>)xxd=?8C*ONkF42rL7B;5qYeWd zqrF(a7Pzab)Ba$zXJV8b|z%Fy)%F38H$T9Rszt`^# ztS|MLiV0r(63oF;MpuIs518dyMXB*oQb02hn?=E3h3xiEJ|MW{#3hJgf96m^P6;QW zlLIejyc$)8!&O-23x1pSsJtACzUD$izY>zK2QY(M*C5pAnke%MS{F*UCqC(+tcr%w zPW#h2UCkXH(oPG)zf}tV?VKPktu3y5A&K8~ZCD5p*Rxc|1@uhKumt)4K{>-9teAN9 z`4!Zk6m`&}vNB%gP{)=Iq;^lJI?$0=s`7e;DgV1fn6)s9?V+JD0zX9Omqrc`njhM$ zfxd<3Wu1-J+d*)PkJj*0Dic1#hifqM18PP9GZS3usaJ5M!T;}YVs-C#`*(N< zkHxrR4U=C`H!48I32POQS2Nld8yL8gdbUFW5PFPo(`96r_v;EJAeHamk1iOg7GQ0u zpqe(J11FHvd_25OfYFm5;2uheRY`VTaI+zb_;kA|bz(K20cPhHl^bxAeGv~bC%FY({!>5Zd)6Gg4JDS z%!-6Tbq}FFc;hhoUYq}7<$Mz)M4+U3_zrjIJv+QG>y0wVH_)**Xrx_ka7=j3*_9;t ztZJc@m4Q1W(976R#lL`<@rxb)b%iW;v1aZ!9bcS{OGk3M^cM%!Arv(#{8{{@CZyeD z{dr`Ssc0OR{Z+q~HFWlDH;`PDEz>oaf^-+#bbA664dcVXhM_;7kQni~6TJxy^bb3B zJfMEPpINJ+^`Jc2xR-hTonyua2;+qPupgALVu9PXhrS;5MnUhJ!K^V#umr-?2o1oQ zJowG%F2{!HyRtz5Gbj333ONm0m#%luaAa6GKGZH*{r;gq0w(P}Vk${(QCZtuM~^QxoOQsR8qxmIo%NGGgMdMfwOTCyDR3Do71q zS+f!d#aF09=;`Mw-4Ob!hoyd;JM2I-rr%Z->>wUW&1H__SyDQok)pE0teK)k`Z`|c zQ1Y@e61(vj%rIrSbg5u^+0&Q2p&Ci23=kVS$Gcql9OL=HK3R=&ic7J|#%Ro^;`X+M zDxz`y@DrR6S_7wWZMGL#J%_RKiT+TijxkG(!V&Ep5e~)FsSMakWCb|^K8yJ7fXQ}! zqL<6B_}aC)Pa#&La)AkIsX<)KMD{|8%TUc<1p>aFNsrwS#HNTG#W+J9)lX$aa%lx> zz?F$vuH*tUo{Ue#mZ3e1XtX;4}3nJ17yD;>M)2YT`w0f+YnMhzFN_25*p1z0Q zeqEVALlQa%tz3XJS--V{TnsQ=hLD6feq5j(DMP!??I0@2zHjHl`NZP*web-(WC-BD zzsOKtb1>oP4hw(HiS?IM=N~Gn@4SC{P{Td3v&^TJ^kk;h-Vr5=_t&W=#GyAJr#67| zrN6kfFDz5oR2eB!&4&fQMp~E@<-5lw$>6%P5+*Az<+*~i>hk+8_*L^3t) z_P=N&aXEF=%8vMRR_a_T4(7l4c}n&?`jv|)xl4X=t8Q#JVT-!vcXK5QWMHB5~RxvUjAV z`Cb4X6F2&D$kDPn+W$#x!@B7!(Sfrt+6*aOzG>p?<@fMo*Xcr9#e6ga{u^(zx@MkU z1^nKrOtqNbdD4dV_~YSOf%}F#&BPJn8Qdw!^hNPBz_u5qE#WUc{vc6^JndHZ~Uu@C-R7mjYfsu5G?WWk2<0Z7@~_+uM#+a zpj7XnDncc^K%Q}M35ak$_iu0@obVt+5`l+a=I$;_a!p^()XgBc1Mk#A+)-ob#X@S| z#%=toJ~_JWrr)v)URr8yu(1uC2Sxu3fMD;gKv!JxGvUHXXKz*e590;u^bovk0IW2f zy*j~jx5u}nwmA89#g{S$!Y1sk%AQ$sNaj?{6$Wu=(@&9?g62x`;j2h$sKCjSnV=)= z;hK-X?JL>ldVR>l*8>`E)nV705i4Mnn<|f5GDLWG_5c=%rHa-^`@#O(8JlWrDC7D0 z@sN`{lw!m(yTr>qf9MK(PtXf{T6Buip%TS-0w)6MV2 znWRd}f5?6FlQ$b)e%+n6780{r%#>+%L2%eQ+%S6J{AK6cgL|$zD0{+(XJ{PT-7#Y` z`r3P&>rzwIk>$$+C7E%{o8WZSMr+g2+v3EynJS$K{#u7&OU?E~+86LqZZd<2ZFp?{ zbt^-ws$_`~#b#2g4ZRUdZrVrMxIOuse6@>Lu_fde-isPx5L(#4tQ}vWk}~n9QM7+G zl$zHYDDbv0Edv^)ARLaR?UXfKyLrki=oSl&UY<~&h-#s!rO;PVt@%3NMQt)qbYI#swOAHs@H4qaPqDW?a)UcIb%B5Om!_ZAz$B!E|)R@p<*JeO^(r zubgzY0wI;uA4hPw3Oji^dfdOM8XBiI_beu)lt9#WPThg{8eJmGqHI}UMa$M62UhCd zu)^<0632P$sNZ&@45H{j10f(e#XYTl~zs z;jeqd?aqpuEj1S9DCKFZP!4iVn9-l0G0_CBix-5U1)YkRG*gal7t9Cy{2`*4{vXXz z5_iPvDH5-X3b=xy=5Nh{u_`;Njt zV->thX9U7vqExwMig@t`oQTBP#B{}=kK^*MEce~NfW|Qt^bfq5g697lK z+pT`KJ0m2K{SEbH6I=yxcfMh)o5yz1Lv|_Zmc^Fo!efBHZx1zSxV=_!7>-%H;j}&R zF*_QEz|xot$)IH2zw?n?-<|v%j5ezlJ`XstzJ(Zl@-ZbxT;7~@2x46Sq#}n_>GUT4 z?w`rA)X@_?p@z!J?L5vGsaKF5^^xB({`1rvx4o$N_SX(6f#Y{BZE6_fANaTu?8h{R zz$dJZcjP2p8nOO(x~RIre1uD&8fomX<)oVq{uwW0Ue?53qDu38(6P{(B5o!=G+g!< zn>ly!-?h!|xpoUU)CoM+eu*6 zn$_DCs^bnJrHGBghyD?J9N=`z`f<=s3jI)W&(P1ArUf$%ic1bdyy4Ta>Hc~c+umM- zZ#M^7A6n(@{PM2ElxsASL+K&?QW;*CK&>AH*w@AKMXZ%1Fo}x;wXf?K|ndd>1 z)YKvi+|=724Y|g%c2*SiOzL&{eamfW#ivkghQFZH69-8SSV0p6VIj!MH#ZOjgIH+9as4N0!R%222Ehf)Oo<|QA|?_YquMs;fSeiPQI40hM?Eyd$>VN5ylDcRJ)(U zoMECsCEg=bZ%cBgqM&(Nm$`dn=|)Sm`1>icDdklX&037I$fL$IDK^R(uAuS|mu_*j zGRaiutTE6v?!sR7YDR6HF{C1_+!a=dWMx`!=jzCe;caA#de_kA;C1=bNF*Cd*B%?%=a8s(fbzF)q*R`c57J*+4?@zm zVo5o$96$2J_r>*tq_LLE3{0&*5Q*FV-QFN-Ec8g5)HucTUqq^KUtOQM+Cc+F%N!VS zSaJn3j!*y1OSCi8R15TuV2&trNrLmfA$w1fE^Hj;*>YyimJFc^Uv$21tkK$f7sTB5 z`{!e410{{=FN2yVr+!d$i?1R?NO6>*=Cm)QODOm;Pcdt@wp7HX2}Anmi{gY&b$JNS zOlvo(vr>7T9{491kVDJj~!ZxmAf`+jMA8OP|d-j_MOOS*dnz#W% zg`a=3Y&Z5)`o3WhCMW^VKP5s=P0UDPvdO*~&~~-q0J1}sR}>o81oXn$Fc1NhYo~~b z=cw34Lil!|owvXiKwo)?%;l_fNW*wg1tJm^m#{P=^)|(LefB_5dQ(bm&=Y|S6oCFP z&>st6NF`}63Be~#fR$)^y>giuWX@nIi@W^S0COR5#@aObg%z;o7m|f*fBKb<*z4(H zl$emJ-8r}hD0-vqYucib^pTM4bhYqZlI@RxyJ9qY>A+>i504=3wSh)GT&?n?S>|%~ zez|7x_~GnhGAJWY2vvox=Sb4gs?xz`@SS8b1uF2_KKF#Hxp(Nxw`Nm(wuUb>+uZLU z35t-Uhl1frS2eE6y)0Zq&;6rxkxN$B_1clY6$vF*;-IDv&8W}~G`9~gR}hN2)10YO z8eJPB_kbCG*451UFf!w1cbLb&pGi)4W3NXPKuz=)()IhK#67m6hnqeEZt8FpJ%cq^ z02WFuNdW92V%!d3Phzy_o~fC^%2;frJzvW8u%vBLZ-L@}ysi z81`32hMmWI_@?Q%#~>jLFQEpzHB7+DuinWF57BQ;-?SDnoVh(T7$B3aAX|3!_-GCc ziohM0i(Vb_D@!{~?g3lIkWACpDQ|eLUeDybmf8XAsf@^>SW$*xsAxEn5x%H3sE!-z z^>2T*l$0@ii4#WOc_`yr%!3{UD{vKz(+EXMUW{L)LV2y-@*;Z96$BE5hx3+8STVW_ z!%x#iX?2@Mf!l?23xm&rtejEbS%kw+<@~F3bl9Sdp)AvOwvN^uuNJ+u$|js(mBy6> z(As@{qvX0*qlqTey)zg;qTV1`3{#*NM3s89M9^Fp;-!WygO!U2)QQ_B`2xPMW33)O$t2^FgUXo$MtW^cW_*T)!Uh6UmQ71c-aKmw7) zJt#qyG=dg3i3TfGUUaJij36gIEc+^^{@2KF4-+wN40cM|=RVw1Sk2 z!1H`+lFSFEDjxwv@En_}jL?_<$Axn_>U%LY80;)u6S{ zU9@E9EqE3OTwMP_+nUGt1@YqVN(h4GkGE={lt0YL9A$hmkwHKCyM4HDT=p5IoKgWA z{8P)Ac@_drGgtHQQrBVpj0=A@(0ps?!ce58KDxIH)j_WDO9n+bqO0iIA2jc2zDFhlNqtcLq}$Q7$s{%_CNjkLgz>&-H&KzY9?lTSEq73KqGj%PhO80 zkxY$v-z4|VkvR=XjWt1MPE6j#M%X}h7x`9e~cSUdD=>NU++;CXxo34?99 z)3)(o*xM=TleFLV1~m%VpF-@`;t=Vy)gbq-FJH zY38x1=HUUV*dlUd$#d#~N;b*o^4=J7Xj35#B|^$xQ9n?;87Wzb zFHOjkCQP@H<|q>S8l5c?D-BS#x0IkIp{XO?ScOC>0UrDt93YZ6AqJGA?@`<)KJX|( z`nFwCGp7D2N>Oy*8Y0cB{FKW^{l@;-RO0pLpzt#hpDxdLkjo~B1RD#{b(@Q&m{MaJ z0g}?sazsU8?G>vD=nrG!-F6>5s^`h2lWiDAJJEGzGVCis38C};#rXx3<80E z7+^H*oroW`J1SoYv>l88>i!WzsH;tss+uB+bz7HC2bNjh}55}H{TXV z0Sb{`38p;|aon-0BpZ|(N~~VGTB&jbOUZ~PJ|Y(kB{Sv*4!_@`*C?I~LKgf}K>@`7 zMhJIZW$co_;6b2x#WYLZ!-+y%@ODj(ny7sjaMTYT8B(53sT+_S+B^!$EU4up*rj$x ze@l@VUQ|CZm#zGVUjKm82988x*ytzeghucks)}pVh#h6w>I*ByIDrVc02Gg)-OzoF zU9n-U+yK~($j?}WQWY!E6g%)S^s$Lp2epgsdHPd*`W|mVQ%(IjQFDH0ifMOBQux=? zm&`56^LqD9f*blCMVy1v_`1(s&h!12O8L#=Fm&!@yp|m#ef8565x#T$-Uzh0i+OgJ z6F%7yeFA--zKVOsU2U14`s6}QUz`B%(8(%Y8>=8V6%2w3kIR!9`fs9~41o*S+{D!e z!ZL*aRw_MF2G`n#7Q1k4cZS@98+Hvn9ChksQuj5-GkzPEYXQgXg_G)XUMy@i0lXC} zVJKz!$*ljm`xmt%RnixRlHCZkTaH;5?a1sIkQxk0@2oFNLLZ~XjRq_h#1FZzlzglD zv)fIP|LG=&gD~5HM|)XIwBs zdwn#|YxZmk-1)0;LWID0sWWz4OJ8~+zKg(s7bHf?E>)j(3=u)75r;!tNs}bf_#N-f zb=QkqyDlKQj#RfsXm||pY0iVu>C(l6lfxiJ^ zL9zV>f1U5Ly%}SV3gH{9b-mZvu&jJ6`vIm#uQ#}G1%B$UVZ5ZNXI1hnSG1@OKP+bLUu1I zEET*rZd+b7Y}xsS^#1;#k1hdmD?)F+un`>u%dIzYjvPx>tBC#UMyV-6q7h|M6c9{M zC6`@E!iS#nptn_#FzM)WOeqpf*}adbFxnmbJlDE6{+6fB2wOCIr3x!<3yB1c_DE+; z35mwKQkk8R``48VfEC#xZ?+`E{^duan}1&)lcz!qeh6@6#ZsB?PQ3w!h#8@uDP1Nj zxuA2u>PCTA)|ir*C;>QPz-LQ?)$jkPQAtQ&kVtkFed&K?U+n0&X%kM|S+3gHz6&CywJK^tU`E7nDgwOP^`!gd~o z(5H|<^Jc<-xR>j^C*lL2!uC@rj`wH-w2Pkq+xI2nV((ZGtcNW;hwkTg>r#y5(GI%2 zv*1hQ(cu3VpPVOkRHVBhXI3A?gGIPL5OcBoPG67@V%=~ZuyXyY>Y9jc z3;A8|N+!}Dgf|(*4^G5k((T`@fP2Epcrdi`q1IYlg$s5o0=&x zTox>DMCl9sJ8W!63)mChC-Xaz?-@F~Sd&T$z|*Dm%PVnlg#3pNZVgSxU(*|+xV$?2 zQLK2bJW~d==wj52d~gAd7bhmpgCM9lFJVJ@n;aB4ms+sArX3_9et^@-MwSU42Z2`T ztSG@ko)=KLJ%9=$5k`Rir>-l07KY{zr%%J=X5kgtuIGPIJ4}pcZb4%f+}KS>a_kNc zg2T8qTnS@f67tzElqXIe$Th_kx|W|B>W)`78G4A*=&!T@6(A;SM+m7I1Ny4d=?CW* z8sYSSd@qYHUmU)CxgLJ~;2!KR;gjfR+Z{B=~jpao_P%G~5;q59i2EZy6` zQM|f*$#tfD4q6(;7#yEKhHh7;S9=@i>(G_W8sffbF4c?thT0_r(vvcnBdBe9CE;DA{}G-0 zD=Xjc7c`jt;cQoS78WA6LRw1)pg`&Rst-aEw&CYZt6ay0ADj2{%F9{*$$aN|`qV06 zW8|{t^YXOv%ba*?#gjHOuM>^LU2`80a+~$sWONq;+B3*Z7k&O?9Xz1H&3!gA-#8P} zKJbFmQ03~nIOL#8D~AI;1>*4FPYdT3V&i#&4_D~^xW(YE-#%li{33`)G7l!XLwB(# znV6#lTN(KdbGH(;e0Tqq5yz=QAcu+BFOm-r-Sf#+pK>JL3HX>TnI`yiv8^1B1aZ+T?c zV1diNumQOyNB#U za_vV#Va?`_yirURWT=d8hc>mt;_+;Cy z35reN!t?)mGs4q~*X@j9t~tQn4`;o2*$>r-d{ig{ARy~NF*t&YrCI`yWlh(u7hq$t zsWjss+#s?+`o>Zz9L)m9Tvt{5vDoy+%tAz1^!E9FY~;ecIQRhl<$3#8?c(IOMVBtW z?U|Bkop%BvqJLLM&Rqgt_DePIQqx6v#{iSgw| z9&8O8Uqid;T~_B?aC%H6T&7EYO(O7KbKyrJZX zMKEIa2tT3OY27XQS8a$;j5Ae6yZ?~@>40kUhVfoB1^bJ*gb3}+NNCI6$+D-KNo$7n zWDot{EjSd2iKhD0B5-2SQ(m zwvkdPXO71hLaPgEL^lQQgUDQm7M`&6!2tYG`*ddgHzqK4=or3<#1HyS0ME;ly25uM zK*C-iT>z*4;|K!iJDI}Sh{$N!Xnv5^VxWt;p7qf4P)Te`gZ%unK}IVUFBc$WuMI7+ zcRokr_o5^N_?azYJTsg?*B@%@m5t+>l^sT$^Nvq}ax~NnbTF`rIdhMn9LIlzFI!Yj zgtkF|Ui8RjeVUg7@a;e|=pfu3=t&e_Cdb%WqKR$%G2zij1V?A%(0gKW_y{mp1^oIr zPK4$oYEH@+`jg*z9ng~njq1=>SpS&wki>_{3g-_`{$i#h6z+u|IxrnchH-Gu5(Ay*7>Y+w~4C^V_r!t%{1 zwI#dXaol+uT@JD%F`NaHPid(Fl0zF*&&r!b%`#b~LL?%c|3TzW_sVF%e#>iNDcT!$ zSbW#~f7X0y&_3-ic6)P4K@PVlq`Z<$$slz&rW4>L{5!P~E*gU#AoE?E8_3oI);%E| zZB;;5wdQXf8?ehZ=>Fx~qqRCKECux$*iwS+P{`Jru;t;vtq#(hRk^Du($|5jUII=S z2kwu(hacKsQK6by--wuafYW;ik0ijH#X=S@^|+5Fa_g8JUY4!4YfqfltA0Yq{|u~L z0uIk_@$M$2BXoEmqMK4M4)q$&19p z+?*gU2d8Y%f8uzVD@wIKn``{(_^oZ`RA@1tD@wBeE@2k~1*PIuNwO9|Zc*So!Y${2 ze$?ihRyue-weZ(F$OzxTCvMV|FA4OR4?JWuxLD1SG+WUfb$jWC$Fzs$z@rQ*kGuz+ zU^idZL#ywU6ts+kB;}ZRNo0>JVn?bdMWhd;?Ew&*< z4TbjLZ3}qLqUz&H+T3R_H^##rGgM&i^o3cQXF@oNgg&RSk4VZuml&Reu*Yc_DsISH z#mqjcy;jIv<;2~>GS1@yPxNoiyg^;kpa7o+Aoc!7 z6o~QM|M~mapI^vu;$nFpEpRypOrmdTP=_|Cm=cI=+^>`c*c&-vwzi^du@p*Bq=7tP z)paAVy%Hnq+xJJFHJM6Qk$M$^(L74=27oq)h?a3&@PI7W>h_1ci?yS{S?6Z?!4bp= z!s*G2<_X(0!Q|s6X2yn?J{Rma;FJ!q`O(7Za5=S#X1_yJ2yLn1`pTvVi7h-B^WNzJ z71hhtH`LGO>#x!M5=$m-U$+4F!#&DJ{kTuDIoUykkK*-Tjg3f1^8rlqW~M%BEf^)9 zzA%LtU``30Dk>+uMdlWWSq?;kFW}q5USC3tvVAIsus6nZ8C7GDOTnpOSfGIc`+g}K z>dTiy3HfaINvmYs)A&ys&NWzw3QqV_R9q@B>ZjM)+kTk5c&h}}UzjO*V-FEy2Lc*y zHKI3%8qFrCN#W`-*@1PtB)Idx34uQv=ua*`Bow+wIl$cE{cWh9KvBN+PJ{;PSnuD| zk5%P%lA4hlZrfR!0xM4KbhU|M+Kc$>{of03P=5LGw``bb+12g76Lu7g8+0xpF@D#M z4p1~+V?=US)SS76?IZo(qX(ViuQ!fFGf*`SwYq6Djj~_8;qpKz875o+@0b}CYa^abGkL6 zJ`-;X$p;2_`$j1s4oZbD-d_@&SAG63bPG%PX3q6z(i-)T#?#$pZ|ihIvklGA>qAtk zFUP;pKDfuwcE-uPQ=)a(My@HdjBfxl1{o8*_0-&TrVDZnRXxLX(|LMxBSM<>ZZ*y3 z2MVNRSvEH@hAAj$-H0Ur4j<83NY-eWA?10tvsgZFSe;Y7E$!T*UF&IsA6MS~4c_LImqDk}v)CKnmqCWN zpuoq@r9|)|yy;yj^F}uD2vtWw9zIXqNf^e5U9wGWrfgI2&NHNza^Tb>uFm4{Kc@$2 z$$3-p@-Ka_v-xc8U1vt6#`D9e`dRaOcVPDwk!I_oDPpj_+1a|TUM)A`0pns5JfZnR~OWVLMINaURU-y9bC+=1sSS#0#q=*>_tf^RPUiQDgHW{d~+ zcJR@&$|cMD-%+vDZdDU{0o&qg*2&%S^0MKX$o5^2$qzFROixRZ&DnzDdu(Ga) z$)jpv7ugG||N9<)XW2R9f(~yRFt{UYJMpREWT7??=ht##uu8w zG-(LKO#<4n^@j*Ih$5-ECK!Q8nweqkygGFln*mpZ`cBLo0+Tjoy>qR|oTQVb|6=ci zSbTbGb`WSWb$DwNpXcQ zRTPSf1ybv=Frkd!Zbe<)`uW82S-$5-iH&`qW3suG_g=3P;SL%w{7F&e~%XftoOw zM9S^$i7*)I9un}rlmBEOzj(Vio0mtVYIJ0ok+98Wy0o6NH(#16vX z*L7I61mg0Smf86R569Y8|+^s>{PHNU}#iID2)F{LJF3L`i)* z0}Fxp@svPJwb=_Lp@+czd4K=BFS)hg@ccUgs`?A4)8V-v=zJ10rvKAvkFQu8x6)bv22`rDMD7+a6c%3qNTiI;FiqVSvV#gr06TRn@5yeTO}qrh(uP|ZY+Y%tBo z-2VcqI5qz1FEJyg>aZ(8kWikTQh#%cUJgJXObZX?Fz6!Yf-{O*W>xqibQynscbfx~8$5yHL(avMQio=n*;P`)S*=OlV z@fD}hF=6VzR|DV2`B$L$mpvlGQ-^|CJ;rAwaqtNN_u>Cxp8zOGdl|O?-=MeIEzWXh4-tFw< zgfZ&EMK8ZS&xNArbA7kjTsa?En*+`C&NnUt4bq)yqRfi!V;fRH^%93&kVb!w$IgeE zS|cK8_^V{v*L14KLD`uLvB$q`Muw10PD~l|yU#l5am-oGFEh&4qd&|A%|^ceK;jzy zw#n}`ThDF=(DyxrjShgux9A0by;4s9(EmEKsHr@|u?%wTmYo7I5;Wi$igf<(S$B)e z?J~BfJByLU{kZITMxddUj#m?Zawr>j!v`T5V-j+104ptB3e?psE7azC|r44Mm?-e)u>=TxlqRu{QqEO|jt}BYwq5=wBYjT%R7z4e7$&HkxD~5C{ zhRO}yuSO#;N%!7A}6D2usIDfd~m= zPnQ+>HJ`}UgE^xMqito9edkqp>tn)Y3pRCzWl!M_o&KLvYeh^efCy6x+YW?Pe%(6z ztfhE@te=`J__;{7+k2}|5OUDtZMg6g6Lz%2R!V5mpnb>Hhb8!fvs;gc8#Q(CWC<9O zN^E!pFFdcAQDLeAL?S2jIBz$aW8no9h(`IC_jObBCO*Z$y%^-aOSdX|H4pGgFP*Tz zV`;M5pe&P8PY4c>fDf;})~Hm$sWF++UuvLRq%nTRZUr;-j6`nvT@EkA6yy$U#xU?* z4^hWVkOx|rI~)&1y#2csH@UgC9e7D0QAaaHUoe!s+0X3jD$&RJ*|zkzT$m?{ixm4! z_#rj&a^@nlm>`_fx=A|l6d!73Km^QV6R-e9xPIL?mi1NvkSWn&;l522EN1ajq|g97 z^2)c!aMOLTP{bEcW7Ip2APyMr)t6p*gH;9a`M1`|vm#-5J_3hbSrIUKqqASy8s-F> z7lIpw?56eNCUOVp17hQ#E|E`oFE#Qo!#ot1VhRL%_J8K;+VK;Mz5YL+=B>FP{0|r$ zJ~bZOC4#jD1kj@yc7N6xha5SpR}I50U%*Ct3fIo2UQMftSFr(Bl5cNtS z0W?(A0ub6DTunlQpI6@wDRBh};Ns})WSJHLs*@-S`|T<4czsHyAm#Yqn_ELx)T8E* ztJrrQS#;2sEB_>J#em&``d`kt2I%meKKiswSw1&Qa z4V67P1VxqIp9u1AU#;#{H#e`ZQF1|umvPGSE+hzX{hm*+ghWBO*f`j80Lk{Z7CIIb zzUMSBmSFQjMX~hB1S=jJnqdtWnsJ0y#jwW6Y8z!K64U?X>0@ayqqoyFMl8IIw!CHI z1-VLU-N)vd>xjVOzqr+YT2!-yG2jnkMMnsUu39lD2kmO%}@W$nD* zouOFl`99=pUT~kko=a}@cO>t`q}=ZO`|_e?sd|+kch$UFOcvE2nf|yVxQ1)&4T@wE z29nEs5j56vxC(l=tqOQ;!XG& zQ_s4dms=l)8~pZTwmMI25Q1ZKinfQi^uH_yZsAYcXQh`B?`WBV1O1M=jIson zL+`#besY6pbHRI6O#m^2v0nv4VHlx;40YU5JJ~M2qi*-OPg}36U&(d9&Fk>+y&iii zbg;1*Ub@kARMzPR>@~%{NGsbMr9C4F)z3~I61II^&S3E*>?9?7!mpjZd$R7u`Zgta zsJKRe`-I=@c{4aaKYtc4^rA(t#{yRXRoHnBzrgu=#8@GzER!?W6=w-!6yr=CMFC*4 znG#=l3PiX>j>Kal$zG+abrj&YIXvoXZEU{9sGG+%{(E)#O~CU=_I5eRfT|IgI`i+L zUud=UpPVwbAj;x?C3GxzVomHkEa(R99w0$?@1!xw#(19hiJB0Qm=gV%xT!2y7IwFo zGEqD4L@mtQErTXdh3A&SSI@scHjSrf3APSxG)b_cY|CS$jSR73!yL;3xwJFETlln= z$o(2y?~fm@W)JJ_Pg-vBypjful3Rmig{8|YQg>OcmV?WD6hLYQ*%1@}!8J(c1Tva( zBCkI;-gFj0L_@hrfjLT6N@jx|={wJZza+fXQ(}H*R*ZQg1K9F0PeMM|q6T^%9%Ju{ zqO%OM!il3ZGszOhF=Jv&Z1I#;zm>_Wv%iAHsMb!{-AqsiQqZF;(aSRzW5QynIBKOn zKq~MWz}g{mBU{W97{+FbalpTw>cHotPruie??=~PZkzwP->xlgDTh^aQoeHKilMSK zaSlU-FxEuk|MOqeivYwr{chruqtx0%@*`g0J1itVd63lVs#%Zx6It7jAAN>j<Wl`QC7e0~UhlaFw?D__X>7WQe)4a>2{>BZm z91G0?seHaJ7)GvPwIk+!ZFWb3rg&y(bsn=+LI8EY)%#rbvQz|Ao4oTvKre3Cp4GZ> zD0A0wsYJY7Yy&!4{hsbYJPV$V6dkSH)7jo`n=nrbP6ih@S>OG<&C*4he^mON;(?){ zj;Wmg!0Z>(`%md_2+4|&r0G?QF%VnGaO6yKBt*9x?4KNv{mCHPWLd-2o>gGnbp8_4 z0(`#mbU9Uq&aHP+c_={aPI2;H6G!(!5w#_utZibzN5!o3HPdme(NnSl?5z~{0M5~p zM9EaTY4?K;xwA-QAoK2)`X4<}HeF(g&k%VW z$zK=8t9W21ZIhd_`m2P!r%~1?DrV0XzD^%S>PwT+^;y&f{Q3!$jrLIVB|b1wgz}Qw z5y(#+avzxG?{|BDIW={;G-z&{8aij2vaRcA1r=5Y)zAhtazD0J25E+45m}LuL)pnH zBbd_MdTs7FI#U&A%nq=68A4{*q>rXx*&j!L1~y`34b6LvOqP3ec9<0Jm_WR&G9H3+ z%(>wDivOeNtOBC!x+wfk0MY`|Eu}Qlt&~VA-3%ceLrBLU0wN{w(IqKJcf-&KNK3~^ zcX$5t-_7Ma7w4S4*Iw({uu=jA%)51X4`UpK9B=@AlY&zUsLc?ikSl-Hv+{X{k&UzV z0)qbKJwnHqfJ{niOUr6^U8D;mr03S*cv)Eas>=O*=Wmy}k#tG#$&g~=<}8aBbtA6# z-Fa6}E?MZigHJ*#0ag~_k_lcZ`Cyn`cT-b~#^JYw^dN}5b7$oFhe7n|Bt}(=Uw*6R z#_|e&hl+Y@8l%p`LxM;kx`|b4)8ON#W5iRo<45S?BL;VhydGCl=q1BIltk9N%+e0W z4T4UO)%+-}K$xZbC(xl6QYorW3@J5zSX}BzBwIT#z@1#5hVS?wsa1O8K215eJrie1N^NJtn#SxP9Z3_U=}Bnl^^#1rNcj?#9S7z_hK&s93HL zf^u3pVmOu)rAA$FgC0z&LvZ}Bns;^SpTyTdDcHw5|1<665r>R$EsM0+O^WnBz@xvl zUx9SwHSrOUkLvh_qfpw}mnCS|BNvIzx&SSZD+Z7gdqu3DAK<{e7J6mChYl0tv?I;e zO8AIv>Vi`NUX++0_*OWrD)A==ahi&?7-M7kSCB1>f@;b5SFgRD*s@{dgl@U1Nu&4* z2}LJM1ZXM zi3dvlH5z>2E|c5o@UAA`LB>K3&N$ks{LHch#CuZ2%ebv*qAH%ak80^oN=I#F{n11CvBWqb&U6R!LV<}(Wr8NZ{8fyz;HVU!Q-1wtt z*Dx1TXWlx>ro45D>3W6@Z+nhAxi7@|#qh{YgQr43U(Kb{q#Q`j3fgUJkcU5S8Zaa) zq1YM8llD>kn{+ZjjR#{7@@625S@$Xdj|o`Tno7KdjlTK@zOw)wneE~^Xp`2q;Hhoz zHW}AE?dbfRFIlLM$$PCik6$4&(`4AjP^_ezvD+9|+Kz6vB?oWg8$U{I_^qFAjxf=m zR3$Sw2#T(9O`4_QuAT$PH>AjuFPuB!60^O`U8gRdoHSGgTy8c zfnBKUvqQ<~xrTxVZMP@~9jP#CSZ>_cmyzNXZn=ZdQV5MuNXmQ7>|lXH5L}xkEe<&w z_{0}YS0CdtVJ^*czx~W7p|~HvqTs0+sV5hp_Qn|^?&rLGzkmGN9Ua%{P`*Gk<7xcDv5uV}@#L=|T!_B|hO zgO36XQw>p@_i1%eHx@UYOqfRLq;ww@Oh0z=+c)nA%mDK)V|ujc$F-nsF#>Xt6n!SO#=YDT>n*690|_d$&AHRIBeEzn3m1xb%EFT$S)= zZ}z9UdPcPDoIIKS^9G03RW%gW3}cWi7LqaTT21>yvr;jipt*5!8DRy{im@xOoePx} za{ZVBX{plq`A(Y>xnPozM}|xVwa@-xkJ1Yx-`M==zk0GhIN?iidWyRl{S@IyDmF1+ zGv8Tn#Py+$hZt+Hetxk^FH7b^XO!! z(G{B$Bv9<8W&E5!?Va?JK2Y3P1%$4D90bU0J$p3@z3Q(wb_j}Q9|ElT_AT!1WSt+j z1NiRzZZ|Ivmz^a~8^2U$%O*t-s1!FPtx(rJLyiw5G=L8FzvfqE0w?cq)RyD*n6q61?6ypngs;{7i8DSog zIjc^U1%M2W!zatcm&+$_|7}gO- z@;Lklmo(~J7$SPkeYQlsDcO*IpXM_2s*=XoU9SKq46aqYp-;4b!fLFs(=Q+uegA3w zy92ThYKM_(Z!3kzRq8Tr>~w5uF}-6tM@tA-B_T{D!$=Gyl!r8TgYv({mUc$KHlp8x#P4%eb28_3)TGA@ygrDRyu{Rq7+(08 z|H@STG#hp9z1_hI-YGpw8thg5)coFYi-S(UbtZT_6bCI6F+5p z{yzNysiNp#a?a%jMYTdao?bYjM&LpM!|mK6OcyZ&Mj1{fM#AX7AjiTTV`4_`s4 z=6_|?T{3a}?E3%s(Cd@!99U#zqul5kKOxOHMT$Zo>b(n#aSqvOE0MB{IpCnDoIvW6 z^FBM==>7=gXY@*)mPsUKp~wgbj^1kF@EIwUS;bqyIy1euAQa+Jjmq?|Qt0choM2$= zB&hw;XQQ_-Y2(X&6o<{kxEf0U?*mn&6z_?|TC(V49Vf-~V2jYrP4gmy9v|kH6$!SM z8}NqbW`}pD#UB$05+|oV?0>%ZS80&gYf#Zsc>OV$jmVBPO1tovNYi92@`Z_%Q1gKk zY?uX(fvk1-U8b6;j%DL^kWPhhRBOBI9e;(YWJ-!_>2&@asXF$;nXTlSt4V0vZj#Eh z37}&kPIkTCScxZbH0^I|L-mP zV5=K1b=$?x-$j$QEbx_V@QU&i1^Q&N44#1Ns^lb=i!@2EN_v3wp21U;VokH+ z51c<%Tp!wfnrJC>z=aINZXL3&5zuLZU%TFP3JH zyNfku9_$~K`4hX(9L@29p!I>HmINi1GNjy5 z9l>wIAB zj72^7NB^e9txr~Ra?1LKH<|P-d7e?Q2^_FgL1rSWs#Hfyq#%^Ib+b5z)JgVl@U41^ z52_y)sIQzMD9(A6`3w_(`XX|ecnYId7gS^lG^O%o0VhKTEb-J-!oz-Lgg?i`+PS(_ zROAUd%+URuxFN>7dsvfNg!Ee5#y9h1@4#~bN76APP@P^y&bOq--`1zf#WY?ZFjmFrt_hAtd za9J+k_;-H`=}ja}9T`J?7x`-4#S?yfJ+y%KunDuWSqV?kNhM4A->f&fZH88p&INec zD0;AZZ1UIwr%#aYIU?2*k-g>|v$Oua44SNmFMa>=qo@BpZsn8Sl(YSshd34)PqyS5 zM%uXkvDhJ%=EF}Q)PU|glti=F(Lyj*yc;oU?_j0rms|H9i_!yYG6@jI|A zDlq~KXGy%6VRm_sMDQ0MJ{Rxq=*(j(kvh!4 ziaE&2$VeA!zu4+ni><8G{Am?t;pk-<@iGX)6#9oF=(o?r6u;~2D>KrMo+Z{7QCJVo z3UC)px*fI;GCni^8oFQHUeJN-B--;_gE+qDbKy#c-eT86}hjqa<(sE$#jH9m%oJ^Eg9?HHM1=)5uBRP-PQC zwmcz&CQ}xfNz;@FAI1|?fc;PpAWXPWY3@x|kbUd%G1{eKPpFd(H8G$)^Nqb~euJ9> zFns9bQBz63y*b~-+>UVZHv1RW7ehB@cjHDvUVh?gHT{mS%Ddi|E&-r9$EdLCm<)MV z#s1-v+O#>WGA<-AS7%FDtWA>aR)eUQm7t3hD7KBT2@L(3{^$8@cS-i8Lr8FFe+8B< zC_T_~rhVm z&oNMMAKm$=1AbZmRhx*rGg1F8Afy0z&M}UdR6|Uf1Z*a|JFR-ABqRePlZMzV99&oU zwh!TtW4UibxQ|fBt9>=&Qwy9$sp^9}@xHW@xn(w72qwyY5Zln#?s4Xd59}trq!z_B z8I%IA9aOtnAFYn40i(UIkN5TM_xtTw=Qk4FKCj+e@x;FwE0a^(#~X^aVi?jQTO*y& z0rN@>C4h}ePJUZlep{Vyoqfj|6!G`!_NMmdqu-5HI#CH^p}gwf)F1f1>l(V6gbuI% zwTSPzKKQ4P4KGLd-1l7kBr>sndLu!K+?TWO`2kUh&C)Z(DBrr;S0Bl|k0UrItY|wwdQFg<7>>>B=s~oPjcRaP8NQ~c zlX?$Wr(Jc0UCljSat>2~m%*rm13=0VSorOf+17e-^bj0|r5;5JY_={@|B@*QTHv)eT;SSO$6=~>%Kg_XWUR*^tmoKPiHl)cV3qAU+I>~l|piP$=MHT zxnD0rlkL);7|6UzeYDx^69+v^G?!i)@+{EGT}B^K&(+srnY#O}UGMIfl4qTAQZIx+ zJpdZ0LC%l5VXCU{Ukb)Xv$S64W5KLS(nVeTPUsk41L?UbVd}Uaj_o!NolX6p0wV*K zp&gPS&fWRovhlxX&#{m8Ka|Pv8}5$wk8ja9T32|~0S&V0qN^hwZI;(V&702U>!{IA zlj0&_%h3=x-Y&<yT;bh_=2MbQy<_lJF(|Bd6VImC%O_JUe= zG+pL%4Gv<2AF-d~0T1;#z8hoWp+9+*+~egQprZ&I6Nvrx&(~AUcm`MI z{WT%(Yw?$T->OglecM764?`)^W)<11#%ZE8?V8$Tt0+9`$i+F9ZxmIQPn7%;KH)E$ z>~G|s$siWxJ@TL%G<7t&jGoffeVLdQi5B=4gb|eido!){HqxbFlyae-RmR_#d3|yE z!_I@QPHB1IQ? zeI-RcY}oiB?YU@1*?=OYrA>xD2ArZwn_8gc1%w18ZMqIvvrR>pliIl*Ke~e8jJ`0#*qK}odfJuAT~pSa$AO8a_jCo=h*@!-1^d*3oT_R{`uFlEm1rYE<(7?Kt z@gV(XTKe(bq1yw;OMmYGkF$+_I192Q7AK=ZXP!uZc4e?!Ro8F>V`e~VgDd5GZpmWW z@Qsjteig-9;1^){s$c)(XQZ>0-DvSP z;xf?T0K^m7=7FZUHWLa{loUQR+N1AHKW`bBRQXMuKugbA70xn07 zx@WelH`_CpQC1^i*0`i%zHaCHK0M9MwSpwp?S9_36Q{>}Q3OY@BC3_AIzDPRg${(z zvpagrm0B72Z!&-(mZQ;>T%M6k=|D5INB#n~|Y?(ir<~ zY_mFb)LgG<=SSxV(kvo@g6U6!D6&kherNz|*jJ$d<>hhS-9vI884)jbbT1A(629^mYLD)X6iy^noy(--)%x(03NsghbF#ir{6;tKRVrIj`=0+V~On^+H6cj zG!HWk9spz>A6N`z*A-rY2qga%)j=~U{NHJFFa6k*!VvMjh@p1z@Z3C)=xNr!`}Nek z{SrVv>}Ga)N4E=S691b@%9qAlPf<)$&@ zudc3#Pwm^!zL8As^3Y!6p*;ZAIACFO?Zpi65ZsO`qUN8M7#j08?|Yz_4Zw@beg{IoM!RJjrn z6Tg>bAsq1YYs_7ndr)RV-xT*7L@YU~@NXFw97`AA6gy$C_7-8WT6$(Zz8_P*Vq$u? zkpeI8b(t&Qihg%rYW`^Y8=Vm=4tlLdPNb|~2vF!Xe@pZJ(9H1F3m$n)Id-(R)qX&# z^jDwgv+u>^TE5A}-D<=L)Ai|_WRW?~CR`096_^RS`^x_G8LIv9Y|k-~oPpfAz5dF_-o@=buF*~*34HAo(ghR3hdC$^ zgAn{519#4EhUVFt<_EsL6gc}vGZ1B|!ziOd`U6o1!6YE4yZvWy^ zTjL@ECE&K#w+jaOMp`Qc?DtrItyJA~-kRIM#|WA-YhF6{Nz!o%-tGL2YMy-`ct;Sg zJ|uPauce))AbWYbe6hjfGU}%olzn^L3Z#NNSQSFL8zpPVisYq9wL!dL01+&*yOV=e zD5b=;6;Xcv_p^QEY3(uOo6*a{3va=}Cz!$3?h-dFy2Y zO$jP8HNSkvf(0K8fhwGORsvue8hzMsz8AO~Zd{(4Vfp8ePT4T2toI6Xda10VGZX=h8nLNwy|pWj@{ z=5Hg1^Ik*wy@ocbXUwV#J~HFKv}lNx0Lc566V&OKg_ajsfX6n)VWh0Vn%UdI#c38e z%=2SDAg=r+dHV|)vNhIB^x)Sq^`WQV<-rsC+B^NF*UmJQNnyqY=T2TtfLDO`b{sx$ zvZ7N6D_}ZH!&b>uO8);Vq;XRvfx(nkk1%z+HM_Wor}C%7)QmLo#UZ`ctw&qp<9LA*wGQiup?K^p>}2zkw_t6&{UWGGb1 z|BwSCnI`BZk{MKB0hVBn)Ptfp%kSI+5DD4weY$4Wy%m3-$pI1?IJ}iIF`Ld(tpUw1 zK})XSlFkp=;6Ep2-jj9%@v$v{H8IR&au_Po?0OnLsB0OsqNns|Caqfh@__Uatpoh| z`o3`VCnv&JR#Lk=?4C8C4)CC|-wN5PsdbNeL440iyy*TkcI$*45!I-5PIQ)Y*gV3v z*L}RrS1P&?v$@jHF6%DZc>sSV0F#sZj=AhG#oQhXLFK(KH*ERc!t%o&xJyui$sq5m ztE-C}8cNhfk*7*vPc))s>E&zi-e{H*O-Cw@{~yqiKjx7LsNwqGK{O`s6q?mt2el$Y zzNa{3%ElLJ&JP)XBh!w56#rBGhFU#KO47xRN-J<5|1UVXjR<_y)fa+;4#}9)9T2%s3ao;yP6evCh%ne_oS4x93ZHn+{MoE#b@7XlmCZ-5 zX7sm`fv!Tp$&=me7$ViptKQ#Y&WObEwYh|mgnIuytb$ST%-@-ouKVWez+SOHN#sAJ zay}dyLk#I~#djKW3ne9^nS?0LJ{j=i5#;&=(}kkyI?VRJt_7`MGF^VKFUC4|>3Z2C zi|v=FyM!TV@>JG=sP>jG`V~(mr7!NAJG6BV|mpoW} zQnx($u^j!y+wXMdW%bx@_e>>+iz#rqhvTeHe5O_bXGbm}cZ9YVyS^{cL_7)cPx?-S5@slE$ zVL@?7tFfm*g@ruq{h9H7X;OBO0c{ckf_gsz zWPO{lyQj}k>)Y9HDEk>ftO_Lw8G$X|aL>=Vt7V*>c|0TmSxtT-#vdrQbaQN8cF>Gj z_kaya5#8}7-tm7J8lS)UY3}DYWXv5sZa5)Aa2zp`nQTLJfWUqVsn#fbA85d9 zkjbAa`;qp$2Qw?{&7O!9LS|kxr1}ZR*=K(0q9OGfVeH6Hh<3vbV3XtLOXMat68%w^ zFOk8AnWgQ&`?3yOZeQK`wp<;rlE;N%CK3_G#PUy!*$teW=)p3G5k$_+YkC6SEka`3 zI@xYr;hN4{m4T8)GN#7g*VXoCtpErU89fc`VgySVIZ4>E1J={hBKnjKLh?m^CJX<9 zjF_y9`QbL zwXzFb&?5dyrUm_bwnF);gbXjD%pF4WA&T{jJh>y2jt=&;T(O$KN0UU%!;OFDjp z^-pg3kc;?rN4Yil#rpNBr}LrAwog!?=Pe`K?D^-4Y{HdT3b;X2z~;1r7aMaRFs!cW}u^9zEmkR_I`X zqVSTVv$Le>UM{07=;+0&M~>cHJ)0F}zdvx7eY(yT_w;Ui_W3|7FhRIkf@KM$Q=BB} z_@lx2%5G?jI4k4ppo3)mwuu!y37@mASPK$s+ZQB6W<8Y28>{{%e)m3-kN5k1>Rq1F z&j!Cf^SA`>{ny%$|J=sYiUv+gWR$9^0+P@HTE2h$ss8`4!^zqf4Tt!L!ch#QLRxsBc3iA!qG;Kr?xPP+R`b*AUv~PoSf7Z#E?73j|({IKP+T zKaEVLA@aT-c11PjTI&0hK=2s`N1Q6uRe}MCxePrQ2#;V-)UZ@~X84vdNO*>_0St?q ziIqFSqZvb#$rXo>#u1p)^)ph%$llN5^IiZgqE+&4ZqjY`n^G)uegeRi5a>#48Q4tY z(IYt7wNLZ*CiUaMR4!i91!xS28xlGpSQvT?oGZ1Qx4-Iz$MZwBuh%(rP3W3m6XVb? zE{h1tgL;b%#f94<*N*37MkoLbWOYeJvup^rcBUDkS{b~1tQUPEZXo+5mO~D_oHyv` zb%i!+jYo0hT38>Fe4c)STzhpdWzxSa@c7j9wn26$+m`AxsAA7nAyk1!KSpkT3>`+v z(;%J0fFIwE_i*5(MZj!6E&iiVjQshsP7U)Yiuy-MN$!_w35YZ|(7WpG96Fiz@Gng8 zWFISx=Vn92*@&XDAi7}$xstC}pZR4*qsUkFTlg1o$r`xd%OJtGxX>ATT<4aneuBY` z!1`^07q-sydv$N8rwX8#Xj6ryJ-Jwf(G(CR-iyeg(AQx(E zpr@CSCF!x*5&Ridi%$Sgl%8*FNqH2y^Vp?~vFjWq9BPthd1>Q0U-d2Z1%kRs!R!kv z36OvvBMNc-TTEyNAmse)`TxhP?}irQMnxf{8n0cj?~)s1eY(i6r{3SW^#~S1rS5nF zFv~C-RQb7Vhy0mGY|a0Wc41QN0=aD5p^tF||Xetxb(Uu{^7Eq(XpO zJ2uxSWQrSKhC(!z#*F{JMPnJPr6Xs`{7~$R-ooEUHg%XRz0=~sxy8HZrTn_2?`fMR4#}kA*)AUYK*Kg?6 z0~*XFqBuEp&_e)Kz;~4LTx-os2AT1ht36wd9(AoK2i_eM#+}x6{ z`RQxXqn@S*^`IY5mFF+06-qf%)~T@To1kcK^;z(>qLj4Hjs*Ui$UE(=YzMbfRkC&l z?U#*N!K5CK55L$_-ehQSTAa|qrd7E7CST$k4rwIkpgYUZn z8E_6#-@E;$pDKf`K1tu~jB?ketbC=;JoPNR+lL`ik5q@>CS+;^8JgJfarp zBZa!95q5RhfU01zgCO62Em{h$YTO43L)t;fInYUpo%+FKrphQ|cG zY;Utmhx?TY@(2%}I6RKqYVgd-Bun<*+mL*gshuV9ls-R{~D;#$|(r1W217Jc!kfjQwf#)e;41$zzG*c&33s=HBku zwmYQFF`8bnD;bC>w+>3?Hmv$=NfMfP-{W?Mi&({v@_1nD zc>eLw`>y%U%{Lj+!ke7r6}y*p`y`W7THPM#S`Wnx4J)S?_h|l(WJ5;_9Ym(34lIwc zc0UOqNa&Fj$NKLLT*}dd7}CzHg?KFcvB*Ex{Zq_~Om)UO9OhEHDXd2 z#q$$rH#+K;Den5!`^}^ce0z83{%Yu{UAHRzd&%d(1b@X?#?vSj(?&1Xm5aTZUq{03 zQ(5iQo-Yr(s~F-a=gK_TpTc}jw#wbg6<2?hn=(TqQmIO6n8d6kC9{>A1B+qYXZcLfK82HS7gGU#~zuWpjn@ zkJD5Y#x0tBZHyCYE__9A>U(!JbkwN-^{_O&)*-L`7tQ3)O@IBNG99&jwH2jY^I$e(4Dh+qAyO{j!aI_fS0ii&W4*&`}dSY6|Z+;W7A$81@uq(KO z$~kdK4I*&<1g51(2#I-XfYZ%#TMNBRpP~}6P@^E;9dekyH50wCvUA~TVR2pbfxIht zkN1%Xp{|7J^X11PBn{SHlDygtTD7#He6~w@3dtfRZh*p?(r4aqX(V!3{THo*Fq3J| zrLfI41C>DeszxkDZ8P3yFhM6JX|lvIpJXOWdPp4b(|dh=p%~0kj@k8l0EDLAhY_Q` zf@y41l!&5|!)5Vdbm8mMHmAqi>#ModI52-+Y&7q|tQ^fOh44PhSpO!lJDbu7>J>u1 zIRLG>#ShEz~e3Oy%^F)z&-1hMDx|85)!{fl&+K8EppHlmwOPO5<3_Ey#-a zYWI9O94dv@y{!zGSggXgZ;MI{lyPA=*hVizKnOj*nFM8!OP}>R>1M>5+@JAONP$S(8Y?G}wHZF|Kbsvxo(E zxepr)vdArVSwAgym$8$Lve6oQlIb`HH6>OJh{uYQ&G_ z!BN{SRVPkKL9C}7<+AZi$Yzk)>@(&m6@Umf05)fbPHM`-o?%>dUTOolK9z$OXZWCk zm`r_R+P-_BWQYf@#6*iytKU<7h1hps{zVXoCASnG(ZgkvnyCP1O}P+rM9Pt{{Z z{*Zu<-K>0sW9obo85r35KHPw4>&s&L`i*w z3%MCY&Z}1)KM){WS1=})lt?>XeQe}La?vBlr{%;*Lp?s&D8NTco`s`5MC7ROS$6F7 z-#Gixij?DP#WnqP^#rd~5xDC!j~5w0y((^Gkv#v$3d6cTyrgrnYW*NG7ST*8(GO22 zxX>8V$Uf&E62(9R)(ym3Hj#R`NQNI#T%FkfU3#INEsAu(<&-O~B1vigo)tq&oJ?M| z0ZcqncIhZ4LQsSp5#=UaWs??9gRiZ*4_o#Gc4;_fS0Wzocic?Wce(Xl&H+|4?056) zgAOcIooMP?5jC^+mb`9s!h+QO$gt>}R@Y;D=vJ~CD;6?AV@X60g!p65T0lC8U-3|8 zV^11`)7m5M}*MuU_4aytt3FnUoEF93c_{DI_Xxk<#0Lv_>DE)!~DP zar}!ASoA77%Vo;b+xm)&Y8s&E+Tj-Jtpw{`r#?5X1wp65A{;*L8H>HSNE8^sh^|yviXj@B<>|J)%{o1Z+x7(od7f z-IWD_)s~y;d-$Swf+~gOfv)9BSSt>^}f5wExR30;5s4Bk`q)k@a z0%nK+6gg5+TTf-4&o+15%1o{&34)5ogS5_?F8{ZA7mh^f1Dyw< z{?2UE!${p#J!k)27y2pfh-LqUfcE=<-Sd?KVPKwH@E?|lLqhSWfvK~J zz1ouBw|o}6k4-QD8Wur1kBf#nNeD3v|!*xo9{bBYQ#2{fdhmt|u$dhzqv#58K1 z1FbS&om?2EswmD!5F}C=axBY*r5mkNioDv06jZ(htNf%mN%OcMfagOmo;lqe%#>o~ zwV(Co;`S9NP|5m(IUhq6+R}ak%Wxoa7nE)Qyp1g-XGc&A0v_*B2@-*)1rlnxLdY6) z1J}Vw3)|OpL(m`n`fpO2CA8dK9lf9cQ28cKq))8z(~uO|)BW!iLNa?@4H0Ng86v*w zpPVzW{oLAdPaH`GoF=a9+601xHaPPLP##R%a0FyAIraU#J4FpKEvk%1)`lMN_{+|* zc6iLcxxr)HRC95@Hyc&X3=p{Uw zoTJkf+5U5#c;BoF$vNB{^4m+v(}yxT;90d^-lk#6Gh z`8Up#$dsXS?niga3V!%N756(e4oM8n04CmeqT>D!X#E&eH-TMld`+N*oZ&|XH{!zn z0sXn_eD4!ZAne#_>+AKFLc~}im%m2ct2z_+sy4Z`=(ItR_>6e2)P4Y=Q|O3CfR7MD z=SJk(d^LS+S}%M#z~^FuXZ_#AEe0F_qG5Fw^`onGNKKL# z=%{G6Yl3Mhopo!7Zk}33@=-9)J7wN zwb{>zFe<{!CdE#kD4__Ml&8x~T78lUZ@RRl68jn{9b39MT;b?iTc7-S##818D#u^f zHxUkqSe;Nh%%_F`(|dH{H?QMPJ@8jX1gvg(E@Wg~RxOT_Jr!pf(vT~ro4lTC2R5Sl zOk%RwnvwGg!C^i@ft;uj&&EP=%akps;lSy5Od9$?bZI$nd*9fvIAX4%k6}EheC&l4dGHzmKsQ^`6u)i_n$zsw@_>Q#{@eUI5Z1K0@iGQ^& zs3=6?NX^Q0Sh@3N6v{^>)uyb&r^|{Eq604igdsDOpGujAia^sJKDA%)E#C= z)Ax#AA>Mw2%n(m|y}&S1hL5|iz6;L1)A*;9fsU^JqW{O#SSAJaY# zf~&A_U=5=oGku-|IiqvcFHd==1HAp9jMYF1w_>t}@whP&8Gibv^h@h6Bw66fL(cqT z1tc05HE;Up9S|H{9)cq&Z-{+PGynowg)A*e9Q@U zH!{#`K=VE&)q79;Ojv@VIF|qiH<#Kp(+)gx&?$--1AYP;Q?|P_X@!Kk6 zqt4!#{-^i_5stp>zY1n;7HDVbx{@hyl1g!>g;N3Xjaq`0RZ0l{Pak<-+(a9BuZffm zXcL*0DV|rN(_!Xs34NS>X4~*e=FYw+B*-z?YwLs+0O(CEJIq5CqKZm^7|4(GpX9-Q zv${HD*QtvF?akgtXWj+U&UdH7rNLN`Sr(5n>mN^^m1616mM0lm_|rbrv0H8qHCm8hAa|t@ zJqn`If-C^tG+6Wpf4EPGd?8z}M-v2SLT^nwt0z zpP1w;L|SI_2Y?=Uz4p0YuGx^j?exV+o{<*}&MG-rvI$WzuZ4=}RHc3bI{PR3I_*Ps zgx$Z;dyR#g=x20va7T3es64MUp-VG<2xtSm`f1tnr6Y8~rfD9nka*ub1Mt@|`FB*c z@pbvvFA+?VG)=*G@d}NNt_L*5dTw_BP1sd?`*`;K_O$8Ws3Yfgvi4XRk+3UO`#sy3 zEa^aa%Frys3*Ee;l^PeDFiWPzq#&9fKTKlMJ-IAIicsZu$O2L-@Iow5%tVFHRMiy$ zvriCn%n^JH0abWBdc_tz(WVTUt+w=`zHYMMf7m|XwLX50R-;$L*D3WzW{D-yrOUny z5qh(0@K-|OvyKsD|4XTi-%oZE|}g$IKmCoPac|-#VGFtCbJ#`lRHPOsI*c^)NK^Ukg73*zK@j zP>|L{KV^$kk-kw&A9G_j@sU&xA!D=H<<~&yJ9i3kn96ijd`A9Ta0l>|2byvOF_9}l zi(=~G{5kAWssJ=Mw)^z+b*0o?{6>Fm&?xVjtn6vtFZqj|Hb}v z#E0p-SG^&#(94#oE-Za^oq>EJ3Sgf889`2j83)loth}Gyep=bKV2jWe^VnO@-(Fw0 z_oM~S?8$CxWTRK&$$&Y62^H!X(dJp+Pz@3E)H~P9Og$ox1vGqS&QsTJe>XI_w)TwL zLX&N~y}BpxZ2G0r-hUK5`#tnl*4v%|gOht}-ORUd7R;0$Y&}l;(lAUypuIj{JBN~b zdU|-)43AqWB6JJ>qZc7@%3Ga0@qs+;RX!3$+f&%B;*PqwFRjc=o<2ZtijL7sjCRO1}`pM}`7AJlkhj({h8KpA>?~IKT z0c0u;?By~qTs<%V3|G>~$43;wV;!A;yW+p2^5uBlJ5X)NvOc(6StY9OB(=_^wMNd> z*U_1swd8kFb9KF~`PVMw){E|8m;Uj&{AT92{_US@&f|pc{ysk5+VyX&YkUFf^6eK7 z85uq==OV~}h_{dLC8m$JRUmp9LG;Sl5>CaVRLGZFI(QSmK)ls5r^>~~Pza3CwYdj~ zMSEqpeHf`daXyoaH|nOqk?=cmo0?#V<6N`OgkaCU5A3s#vgWHinj^LQsx4M^omhNyQ@!RHI)pil7ar zkp+AX{ywK>@DVH+CU0bS&d<6RI+g!1@|)X!BGL-E`??v?-_k&gkRKFD5+u-MO0@(XT%_eL_0J3giZVs#whVt)a2Xuv_za>(HF>5CqzD<9KfkW@48@+#gen52kcjGW^_OR9K z`fUMP;`pfVO^Kxgf*+hQfw0qErLE9g1Vp*SLz6>#=7~H&3#2j>lghgMEpe@0_Yddu zL3gs@qVKRoG*#E_X$_XwuC3#)+&$O3Mp05Al?lop4-TY%j=@9obyZ~6+295o2HkmD z(9!mxu>xn<_3w{juQ_Vq-uQ^-J4c&>XE)rO2(Gt@3)`*4df@b@v|@3jOH62hb%$qy zrlqCVw1uUMuf4TZ@>|ymIKjn)G0{Wp`~e3T?lMPu@=3ywjvvIWn*W3S3G}L4BZ{l45_4m(xB1}Bi#&*fJk?}lypf--MQz>{DO04 z@3q%@mb_Z5&f3T7PT{+&rG~Qb(HqW`B8p;DG-pa7WN(r*Z)lNmj%^{|rd>Q@zJSdX zjIqFGFi%E!l|rLyE*H)i*;#sJ6wySe+GIJsxe$)%HzbrGs2-+gUv+uKn~?$9NU;8N zXDhSfSTgE>b3;^Wyh-!Dn%6nyYoDJh03fBNA}^!={#fa7BEtp>R!_74$P`fW-7D;v z7&*Yvv4jx96Y+_Vvk?WhNXP=G_iM74PhLh|^i{K3INeA`&K$73a?bspE@~mPREfJo zK8mW{?9q>aUJd^9C4d&Zs{vy-N*^k!u1>|4J~sR{Cx;VJZ&p)6W`~#LM%DfA$>GVe zMzdj~?L_UM`N)??0MTr&3}Tg`87-s)GvRPk_p8N4q<>uP3ZyCeL>Yg-_wVMWELF^^ z6@IA!(%iLK-|2l^Bo+bB6q;2ck-dDa@Xj9pcx{Yy{4qv|8Ai4#z%Ym>f0C)W4k6hECvFO3Rk>C4LcgLYf{*2W@6GX$8SqT&lqLA`Vi&jiYZ z;KmBl`v4Oiyrkd@OjJ%PkV!cXQX&h63U<7$i&Fq-XN&U<|D*e9^R^`^p(}#w$43t3 zlW|)^LISsmQEz4FOmeyWPW)qSs_YsXyayjDHH%Z^03i5`8%VjXv_F-(Q24N?e+QO# zb9_K>xrW0qTq`DVp%kq&%Yt3~6s$MX%K%uoRN3Kgo^f#3I~>n(h(t6*06HAGI@Uc% z@6K#`)wbqshR3KEWB+Cm#?xpgR)7b|MEQxjNQ8Bw%D6-W-!tQDb~;r|1L_>9Dr-@j@KS@5}HL^r2C1Z6%6d*jsMdCdPj`D<2N&> z6Cwb(=Utw&HVIA zufa}?hB!XzbKye%t5a+SxR~fJJEhYLo ziTI)qEF`!4q$87lT2YYW-+6szz0Z;c@GgKB(YvPs)P$tG2r~|<;@$e;eTPjC49~Nu z_Y8Y&Br?*KZ0=oavw)<6Ec;pL+t(VQ!?x;V+i&QY_jIFUQ<%%PUamRGPDuuG3%&&L zr1>%-hF{u~LVNa9JB?THBnzOrSn0qu>5rDBhX;3LG&s{qNN=hUJsm9Ze1AXx+pJFV z&xR@zTPnztxiALPl**7GnGai#NUrZj^F3GND?O_!*if#HJM$5CwbrwwA2V0&o90=A z$<=Wr5g*AooA-x~NJSb*tPz-QU~2lz4(k^XEwAX-;1AKGw`lOcY>3kUuc98wNC$SK0Ro0eEp3M zkdE??+A5Hu!!C~HP7r9|dw>7a!gLRiC%%ALVKfF>)|+MPD%gL=HD$Tz;?xj+^q~=? zX$h4@m<>?5-7tRM1kx8HZyj7G z5L)ejQrl#8i4LZZlqdlSz$%eZT;(M8W;p3~NR8L&<9(76Ap}A;&l8Wm^Zj}lEEz5a z=g{E!&z<@B757K;3u8n(L|7iu=E9i@e0u_&_R8cwfD{EF?^OjYr;n{H7}M0RHI*5Aji=^*H94>zZ8=+g{?ewHWdb?UGgDp1vGag(`3Ache~qF~f@8hAFRSMMvj zGSIPMfttK02E2k)kyrtaV}#<_ya9+Ca=u6Um8h9~9%-rxEy2`aIWJnNZn&n|$Rdh* zysR7kH1W+F%q2&U3|AqHw2BR;r*UDFSpV%k>!#oG|y}RuX13e}XK{6ya zG`CaR_ygme)ZZl{!*e}anm62&!O#k-gNto6UXQhIzmEA-jJ5bgSU7rB)iG;#Sh3;!1Ij3F4q;QOAb@Q?TCB9bI;{zsZkb=YGk^PyL9QwgUBjD;BBf8XpD#W> z7Ng$x+x)XwEg&zpG60>YazMpN;oL-4foQ2oUnuhbq^u?3XNqT;17((9!{*+ zKB)-)F6v}IT732L-~NwX5eJ}5AISyyt=S#o`RVihqA;x!vQ(_$J|R>kMUlR;17>4k z3D``@mk@7Oj|($f^K6yTwY1D{FTbX7hhEsX^eUec6m(y!b=I%YbDb@d0cCHpwK<^XH>!S}0y#nCH!L0oMEHr!$|vec$unXxa*c z{Em6;!%{(}s`@)Wmuoxj^ij(&ok3V1g{RpFFj0yk1G}^f~ViTLIlENAFQS8uT z{P1?L1TFZRgT4KblfLJAM@MU`i0)K;Z{U@}xNdB!cw}qulkyeus=N5_Hk`kAW{eR( zHlD!!IQh&R(1y;i6pa_)Na*b`(jrsD;3In^jwK(O2&e!p4rtv4M69kw35^Y#!=>K4 zL8a>Uf1O|6Ett9Bok~6aI}3jaj*`2-`)_rXBdOt8TN#4M*D8`S}43-k;q@AahL536P{V9^}aL3?xEGg9cIf{Ay3u7%eNdvULk|z7CrAYn6@p zY8L#s|9l_*@-V*?Om({-;Q42~uP@-o4mCiwV&)&>YMu5e4&!1w`flwltA|Bfy}WMn z80d5#V6zqZ|IaqI{yIcud&Eb*QruEbZfg@7hH$(*aSgd+Wq6?)UJ6s)?=B(!hdjvI z{P&saG~sDlhZal>QUhbZ-8x<<6fU zW{s{;5bPDRih+!O);4f71=V~qLGgxR$W1)MAHH`;yvRrLeeD{Idgiq5nT0%{xNJQI zdHH1aQo(d`b&}q#DSeGd-!>nf!+?=|lvd*u$|k_dRN1VxFkK>u6Kvf8j55zMMPWI} z{(;--P#U(!W^5a`Xe@Bq# z`OEXhORynQh{Nf0p9p(j>L5bVTrrx+55B(?pt}4J?{!4Y{qVYGZhP{}YgEro2ew27>vxP7-`H^2 zR52>q&l+9c%GYN6`X@I;w&8BF{U`k8eyU*j_W5!F2{JvuwZ1)kOZzKd*UnaIttn(! z^ebrYT3$usPnKcSqY%Hu{)HxF^;p^t|BKU%+9$Mn>JP}q2L6K&rv>=rW17p~r2si(&}sg0G^mWxb8wA-V{8A$M+6gSCOS&{G7Zjmmn%n|O9$X8*o zFZCe-_?Y7FkB%YkM(XQKq|a9X5dnawcPxMSsg9z3!%P6+zujSh)9a$V?wPcu%cDR#2gMhh}I{t zgF)m*NQtm)O=H#wJMU-^-y1-a&=}Wr3{&WGE?0T0lqv3D##At?GMQAHf-Ibp@)2Qc zcGx+}raXHV3_Lp?>S`E#eNBsUM+*ute7wJJcrQ9hwmW!&&3o?doO$?ZE?eE``+E?d z#+y|(sMlL)gTLaTa;@)Tj_U{Ux&*fxZr52aad(d4DW7HYICnic3Y_&;(m#RCF3^&U zKgd~+u1Kr#rr4X!$i{jF5yA2e5QNH7wtc3yKVG>Ir5cu-_jage@)_P_VVPCm4TqUv zI=Lf?=E}zz)EELkQ`|MOIE{%%$|E$OA%~h1t)G8x$%k=Ou`eR8a@dL zoj(2DczM2E7|tOvWxYQ8K+tzaoPx{`)rh=a1gCGk3@bw}BfKyEejl z{+`B&WOW8yY+*@JzJDjdgnFd)JGKIwHso*MQ>LZjWe6_^bY3aa?6hgxdx#5v>C2DF~Pk8QCzLlwmlqz>VXra9`mmtIq$hHRn50+#Q--ot0U z1i7niY~s6^hzyKUxlHVaxyE~s=G=^??KYaMS%Y9_*sHhex(}x{B720w9#Rj=p>k4q z)4%h=cyQakp$63M>Se^VHYMNbSP}UJ%Plo>Se~f-FwccE^FBi?-=gy}mpw$|lMe8B z_f3FM4J7eaYGzDo1XpR^#8&E9&NQ7l8c7&lNG!XFCemN)QYmitXf$2M zHFG}mVI6WNcXPV*a4Xdlev@3zf4|pp@~vW98L4wv*B>7;D+M3LB5Nc1E>x%W|JYdbH@cqNv)wC3=_Kuq&INHOQ!kJF zc49l(C+RQ#p*2yCltmL_HDqKBtdez+!igG`MuFJdI$SlT-I2hW85!|LtYGyvQEpB% z`+==4KVN7ECA|2i0+;XCFmZ))(919f6el-K18VWswfX}o@N(}lcz5*jG-ipr{uy{_ zOM#dCxBoyNq9EA=7nuY!kAuWw@z`G%qkywqJ;BK$v%MBr;GzhvOZPHqe}@N(`(5yn z;N9~RB1M1U|HmN+^_gXb4jR+4ifa500`Q5TVnOvlo;iwe^rsrY-ml;Z=zk~*5VqL> z6my)kKV9xcP`eR9D6oHdcYi_FbOCb_;e<_!^G)_QBNb? zS}`5?aO&^9OWeNFfr$4k z`Eau7_TtXC2a`cVW<&d=5}rQmRfmi9lzcddkG*iDom+es(MZOnUejS3L<_PnRmTF}D?&w|DGS&Calni{Fj zfQK6dq6!E1gvRp8=L+mu2pa#gYY+0g2v2eJv*oOwgay_SOgW(_RNb!8e$A4&ysYO#poPQt=ZAF z912#dDVamN_J%iI~UgNLsG0Ux>IyD=zNd(H5S2 z`(AdqEEwsa!2gDV601OaD8A!qVkb|?#)PYaW-UvjRm0<$)9Md~+hc;dYpV->$Sn9B z>FR=L_L2utGu9W`43tiD2Ih51oaXLNi?~&EIv%{_fTT=S0tVV5`VdiS$Bhc|QeYLg zj{H0pjP{cy$q1-l^mih_xrqyW`#q6w%(laTsysTkfkPs6b`Et2aL%K zJuSV59G%|s=!CB|zn(0A?@+xdCO$Mm*sDHi{iJtL>!bHsv7RRBSgkw;Lk3EOwb_gV z`@41F!h*Xa9W{C-ohee ztni%>*7w{64-E4+16b!R*r%Kz^5UJNJruS72ENmm+-bW*%}9Wd*k?nC!TU53wZy$t?kxY-ZRq3Zx*oj>fdGcTdl;uE5H1_hR;r)0u%2w^wMq8{ z{er4D?$w(54>F$l&3~KJ6$@=+H!~TyZY7)odFbfrex|`=4`M1p{CPhuTa@;otiV4d zBsLRvRu!Va>PZ)$B2+=Re$cmnP2`aNO5^Gb5d?$2W>N0~bs`wFw!k+Lp}@0l0a2H^ zkAtnhQ9B~YIKr;ZcT?kJW8RHCu7J@35b}AY#jGY$V#*pa;CG!SmiqZ!12;7R+-Y*Z zAEeu~Cym-nxB2htlmhZLAT3=o1*j5(y6JHKK!xW)8oEfZZX%Q9v+-|e7J8E2==!MQ ze~`hOq>#ql&Jd8HY;qmZ7$9K&lSr<}R0IufU;uFYRiXJcdv;`LAQYH5ow4$!6Vmx8 zJso^?STV%z^6Ea*_VH-9C*G_5?xlp9EMBH(Y5Q?3j-ME!CP!!eTdP}#X?|bF!9W!` znZDV8P6mU^&eM8sz?mxFihlJDL5oQv9ExNz-S>yMD4yN%lE`p$nxsXv!Y3>$o%4~Z!n1c%Z~ z`qk9b7UJ0oeh1kcP*SNaw`z*WcU@m29N{i0z3QDEidj?#WA+;_d2pKtP8o1`ts)uH6fI(O9)n(bt;{rkf@}6^hp>(dP9HTZH;E0Z9jEPB|mLF^RC~VWu7&GZMl#F{L zkRbC~?VHEfcBZietw^!$)B3HgGqox#tb~NjvV<3&vD(W)AbmlZzQ05acz9A#M*?dR z{!))O?}{9pUs$_M+R$#tpX|FKJhQ947&YG@^wYbb7f;sK!(?cW|0ZR)qA0A*V=8dxw?32w>$UV;b&S$^E+WW$4683vp0Q43D>h_cEN)43c9CE) z?!5chxry%Va5dWY?*&J=n6>~12se~43!U^tTNV@S`^5_{+Vj;*JPNc{_P54F@{dk% zN}1=?K0&bh!Iue5Lmbs}$BU6Eol7Y<4nEZvy4~%OSD|}Tbm5O)&fblZ@JoCq&}pUa zJ>#T8sd4{S{b*U-4GO1QdS$x$2IW!mvjz&Lx1W7KW5Dq0p>&sxHxVELH4uq>l`7ML zy{WCdS;|ov5%HHeKG48^#ESS9^q5rqdZ?uL%e2aN0{6B^oKLU@wCE$!YNHlh<@>HQ zb8(;RvP^pnoGbV%#oyAd-#6p40Qd>u0t?0m)z zcsCMkWtv}iJ{7V#oqrV?4=ceu`2vq{*JRO}lldpfB;MAldvC$bvd+c3 z_C5ALDqF4%d{P@jx)54J%sOFrC|#Dy$|)VtfquRb|G@n#*nZJW(Sm0jb!GLK5?Z0U z8+qEo`mfZpKyupM-|Mu$IhYU?$+?Zw6eEP36dmx_?-2&vbDtt;P%$o1d^q`w(qPEs zFRuad_Eg9*n0z4(PM?pz_za=Ixa>g|iEOAu8oM^_`pBjgP&Hzh^?X@!G@j{mU3t1< zrLPCe%&hwS!pu6%1t48E*6af&9@-AUBawy?)c69U&?t^P|4NK5_wdf z0Vo>$D2PpG?+E9MpMT$wT{?>&p-mB1WJ+Lk!p|+>19zXw1VmQPRFL-QMDaANtiw#DBm$SUZ+OS|c*)5}O7 zZ4bVug?ps~KA{f}6{N=xe|vVb(IEO5eEs}7?T;g&Wo8(}KQxgYf-WbRPuj-ctXXhCC$FFcNFlN1n{t(jD$N4U<< zuM_LDHmk4DhU!n~;3JZZ=cYun%^MYfv3s5vJYXYrr6tekmSBQFXQz?|t07fCT<`#` z6nLM*n8D;HXj6k6060~gjyME)`L#Y7s!f7m;-Z)oCVF7|tFplI`88!j4K5rAew>1P z;*lEUA)q`LiGQW&-!~#Y_$Q3iWQRxruLb>l@8!QHKfFY*Bah%co(WaZh4d<%Ss7Mzz>no z0x0-CSTyqr!?{3=a*D4X2UIuX3zfklhGM>mdug+TxwTc@pXk*n@C+8;)q+!oS|+I* zcvTzlse$Rq!f?-N7YLeN@!vr&!Z9H`g-J;2lxw9z@B)yhG3q(A;n;}YXC| zjR+ypPnjc#9<Cr|02+VY2yX8bCgBH#^4_Bb7gE*LF|vlycY>ov;T$JrhJI56cW4PQax!WO4-X; z{WzFel+%~tiaSnPp(8UjnP`08(*M@NAE?c(Xu<}Z7q?8599+9*PkHy26213rpge45*66*4Y|N5h7WfD`P;G?*0AsBF z_wbb`T1EDyn;L4R9qIklZtsR?k?efx-`;?l5#`eqR8R`VP58hnT8Tjs@deKHF2W@= z!UD;lD&xar%0IRCZS1pL>Wp@(8}+WrE{8?Ahc#&eA`mFQwtVs%6X&KV`YO;rnm};E z?}3DUOZ=cm&)r{x3&&0Rh2_b8qCLZN1Yi%Maa8bDfmU5}0Jc)nE)SsN+dxy|jeS&& zQk~i@NQ2lHDozM-X+(#cx>nB7Egk}U$cXX^;OraYuN%!`?DxxlQ%ElUZE=S{1Hbzs zCSren1>ja-YUn+sW4h^^C1$;+iGVoTW(9JcHB$hVJXQsyrOj`I;T^E5e}!+yKtg}b zEjWDn-DXG@G;8=hbA@7#%8E5DBE4d8D2^N+pI4RL6KWd>3Qw%Ok3sS=tQm;&=87Ol z@ePW}vc+cU8Lx9oM*^fyrubVe`2_l=MQSYqWgCc!S}LiXBA0__><}CM6c;LdRIdWH z2u1sW2eB22QQPwW(ZG?|!l-KbkoA`&rB15MHv}^Ip9)*+3ihiE8RhPe$Qe((T>q){ zHz0LYA3yJ|23rsq`w<`B{xts_eSG)+9kVywh;R+P)e-i&rh$gR#5&~cNJQ)afnBSb zO?~%FldB<9{HNCsw}znVb&BX{7%;l1RssA86>)VT%&M+ncB)U&n-j+a#?`E22sbA) z;BIX2MLG>$${|GYIHD!(^*SfqP&JGjTC<+zuT$;bP;u2;3M|g&k-%{{Yj>%#^sc!3 z(t28H;d{e#tZKQlpj0UbgOMwwybLf`A~Zj20v@#g4Kr!p_6HI$jmI@C4jJA3>tQ?y3*Y~U;o z%$ad&Ge0d9IC9vW#q1nD<%i8@j046CuUe1SlcY3?H`}BN;M7MNOgAb>2vpIi^$ud3 z#kT@x)-SEnvfgANt!f5xF<8!&6RYer5?7Q!z9k*O+-*PnWJwq;7OQ8FcTWH3c#Vox zPuU^g${L4drI*PHFm*0`CpGW?Vh3_{|B=2&p`Fs}SQVdgs=ZLQIGdTs!)FJu#oWlA zAgX~Ws>!w1bVo_J{^;j~wv{V_lL<|>Qd_$T^f|IVDv&P|lJ{=iXtnaAKmS~f!4SW7HM|{4I1L8hSRM~#TF1SeS{@FobZQCOb(^IeC>p(BStxAqPD~vPxDzvg`h=mEw{%ehK>B?c zPAm0M@Zcq>WThWz@JC~ge)oAQT>CKRGCZU;5a_u`xG}qtA!X~mim;)AkYZ_^%9|gh zqIx38zc0cn2ty(YEYi~Mu0iE`Sv*8O-MDk?ZT4xr%OTW=HQFkqJV@kYC!wIu&&Mfh z)U}K`D-bqL4`KZ`u)dM7?3aCtBKvq;)V4elJYd*-;amG549Q@hkN7H{_2nX_{n%5Y?QDoUjHpdmFu9qiCY{6(C`;K)8Mnk_M&GxW;qZR60;nF6&%SH-d+QNFEK}J$<4YYjOOeUHM7v*HZ8mo_ zVfN2p@Xac7RBBimSND#L8pulc_@3?pOdrgQmj1L+gnd8tLc1D#!F+C;+3^$ddT}RX(++EF_N+@Y?ajZqOjK01x?qgh}67Cv%QW zvDv%#s6mD#N69*()q!4>81A-@V+9m(KyQD)cQi{paF}APOV-0oCtI}^{)Y*QENt1K zE0LuVTuVy6H1**ZhU@3Z0yy9%wK8CW&C-UkDy5+`(8i2r4`)1}^)Hn7J41iF`W{tL zk0BYhJOQCG+M;7gnKPGnR}M3GYSL?L!l&vq-z*R1xrkZ{j1uf;3LZ7fJ)HHf9aD~G z803}01WX+36@k2A`W~N>O!a??GRr~?vg{1Kwg#+RXjwoWbC8^p7i#UBe<$lvJEmeo zNPByB1@5z+XiOUziv;{fL7MYp3tp(20KCHUeTqPva^8Y`q`f^*EqnqZTfQM!>G&yq zZ$;ZiBDZt6gL!VqKC0|hQy~$yVw6sl^}K4eC9VD`t7rtVb^`nivX?39!Ezn_#Ic|T zX=Ot@VP3ON*8c}yNrrfUQ?XzU`Xb35444n>MD8{!a;8{yAFWL(g0RPwu@v?EtFyu} z5~O*!<4Yb#lggj^(xH>M;yJ)D^|P~rmkyGi!_F!N!1Sm2(-&k`Kjikqy?Pie6{Hw5 zawWqq@kbT-bCFX5NmFAmg7kY_jzyCLjMpW$G^8I}2(@R-D#W@a)OGV5`uFbQe{%Q4;9_=bpde2NM{uWq{oD~QT|rjm&P?2F zYLO~dcZTU&^UmXxdkKZFLP^EQ5*<^IawwPxGKQL%Lb5&8lvWJWzdi_k3*co9GP(q+ z#N5Aa_#1TNo4QNO1r|jF{dT8|6zl?Bv2`$2+T|E00tg|A#Y&yu1`QaX1kI}4AF z9Ng@&efip66_08EK7c<0gjIu7UPa0T)~8p=32S@Ku2;t?(S>)&Q?sJ z@VapeSAMWrzS9c%e2}AD7;Vesrd_S!mSas>W&iABEy%oD;%mEncZ}&egD6<;;jcRv zmtn@onU1Iwe>D?wF5m<|3*jmh*RF-sU2Yr1Mxmb}^do&&6i=TSi{?b&1( zQF}k9*c^P*ga!(lpz|Fq_v@}fhCML&(ojqgl*BieN#=^`RdB5OG180*hU}urEZ-10 z{#rH?k2*yaTv)yAO1^?9T=tJkgS|r-bOmD?sO9-*UNoN-)mrgv4>53pO$LezNCth1hz0mx3YczyJ4D|zet*9-mb7xp}-H-_wUMF zwZB2&=Tm%tH#Gyj9pl~Rn&IxO2*B7Wi~~-lcpF*U?A(%ZuRW4o{|8v~($+qk8Bwd| zCQ2oO=&aMPSVH+xJkxS&xMt~7jR$=zmzVtj#qa!_Nn5mV!&+^VCh2~QeUz-{A|T`N z9BOd~!-gcH9sdJnHje*v!6K2kRy#ba`Bvfy=r&cYuz2*0R4!HBc9ilk z-$hP1ecv){);@cU;Rh?6D;(c;B-Q>eEBwmY&p@__6d7yQ(h5ugTj!lFZvGMEsh}EB zg89=0BoOo=HEd%wS{8{7ms23_6RSzLiX3n9SwZGNJ*ykQhaRmU(M%n6UY+KBKmWxP zATl0=>`$L*)=)M^+;)8rlxzn1A8c%;a!~86D)=yESIpRF^1KN-*z~7Io-MJWZX3os z{av&GR;*&w7qrCUd5xZ~*tZ-E?ToL$;QQEF*jN|rbh+JQ}p(RiWg_Vhva(~K63P3P5QcOxV z#z&NDgAz+(_`YCNnxP?TIbcPisXDL65=Re4tFkd~b94)??}Bk*=*)$H%MXz9=YC@Y za=vKZB@VLbSv(=f;Hf6G0uZqjUE$Ra-`dLkO(o=_%As{_n{&p;Xb;_?aQy0QRF zW-joO*6$YLIj*7XHQV0w575 zvr+*ph`VDZi!kB_XzC^L)^mA^n1vJ1;y`%PujL0d3xF1f>#3&qy(E1Mz2pnpEKjqr zfYyKOqdSah;r5mTK|kwyLSswHtZmKZ#m{KwLg`wqr(|=<)d*dkHK1*;nmc`~ZOx>d z4J~(NU{;^~s0!MxIb}4|IUol0A43c+3$gs| zcd(G8lcU`?)junJPxFqQTk?I$?gdU;4IJTiO#Z8#Tb3BpYv8ofBE_vn4|Bzj(!` zx@dycKy%R}^ba%YwCt+pubwFj7OccSBhQ5^*Q0CgSFoEX+zJcTa!LeQ)N~NjR*EEC zwU3k^ciCV0NVbi$S(>PAw<~I}_GJUKc&J(qa{Us#;PfGtrh+sVyw$6Qj3V1K5cd<7 z+#nvja6c>f=G8ylGaBKbfA~4x3jSHDItuQOv{#O=0-Vzo`KA>@BB)QFYKA(z^3|}R zW`^(x)4+mD<~a_dSZ?Kquk+oP%rC}~1Xq4nAkUFtbSmTz6(q%mX&48&uUtw3<-cp; zCw$y+!%l?_&Gm*^sowRbYRS*KE|t|RBUpD zp!^Ohj&nU~E0BB1EwJMf-{zS`Ba_OE+_h~Qk`h!cLLpWio}&T!NZ@vVRZ^K{$k?P4 zw+j4YbrQri$XmmL>Gc?zt0}OtYlce*cKj@DRQb~+y zp*fQNmboIp73T2$MR-uEahYl3yHn7c4xF9X4~H0wpR=MQ`mWLb2~iz4?NgC3IaVqi zYH^*(#*s6=v!o2rANmuPSO(oav z9&OL>O>MQ#uc%*19HrwMmF5A~q90XbE{zHuV^x*UnuOiSpOj6np=b1C zHzNTe^ZC}}>I5bXNB+LO)u(j$Sh+%_fvzoW(LV4goA~98lQmbrF_aU}b+vH=`)UEr zEP9;7epiCAUhZQHSgglXE}a-14D-EG$f@}PkMkV}w`xL-R38jNHZBecV zBgaa=R#r8QtF|ONcpQ=_=DtF5Eu=-Yx6SZcE17kpWTjPLYpt+tG~M!0Lrh)SlX`v3Ci`DY1 zTa&rQRxr7EBGs1Kvab{HY1v?o%Ex)>+~J~BqG5Q{>hIpgqsp(KMM}&<9~0}}->lf@ z3^jkYfB2>_G%jxiLE$xitiQGPnAIL7cUD4g@%+$NaARV@P)qIkwR(*mGUR~k>55y+ zPKGrA@}%w+A4+9XGY+O=KYq?Br5UyZ0>82VGmMfD?y0~c!A{v{WK=jtIC+j~% zeSE3}Hf%Lbk3x2j2=`y$oHBljK1>Vr0zOY_aao|glU`-=cC&eyd1?vQuZjyqt}dKk zB0pd%+Dw_Ae@F_K5rlummUFjrd?n5lXH9Y(fwg!5FOdk?{Cc14>f1~It$E4}GH$Qy zH$4{alkOWsB%3WyS#f?{)d}Lq^oZToqP+>XNt?`>!vn=|(kr3e(&6gKAb6|$Gw0Hi zs~{*Z;@aoS8}E6fI+DsU9$vLMn>%s!;}SzJ>FC7LK3ZZSq6M$m<|INzy-%3GfLKY( zqX|{5^kBnRWm)-i|Jgyp(aIogxiODdN*e-3ckxr$rm`r^&E?us9BEi3jXx@-P3MVY zW42WK^-e3m_VTX9SGj|-(#y2ku7&D1X({TaJn%4L24x_b>4lsK>i_bWpx zczL2)O|k5|gGUk+W1N>qobkOSqgS9HPxdGVy(J<;v=)*#F=tTb6ED)9O`bQ+B;HN~D$K@YbTV;h+coDdDd&UqyfqE+{)7R2 z7Un=p9-!n_g#xlMxz|)D>P9$$+rBcuAHDAl{mR7>Vz>&v#((0d`!b>=m^Ry&VF0S; zc0e{~F!2@^a3fEB6l}E9Dw{U@@12HVvo64QMWl?^Sd9SHh&DQ|f0;8zb@z{VHrijilFx@sMNjd}H0wBNyd1K5YJ|6}vq;rpI}9 zIB4+td4geXhc@S!g>|8Lmqp|fOik1hiJava!JL+OYim=Mft;5B0b8#7r|u6Hti~8S z;?=34Ns&ElzQ)!jQe_Q{#>RBTC`0;&-NTPp{++g8m$Opdm}eas*|U5> Date: Sat, 10 Oct 2026 00:03:14 +0800 Subject: [PATCH 003/189] docs: align translated README artwork and layout --- README.md | 6 +++--- README_ar.md | 22 +++++++++++----------- README_de.md | 22 +++++++++++----------- README_es.md | 22 +++++++++++----------- README_fa.md | 22 +++++++++++----------- README_fr.md | 22 +++++++++++----------- README_ja.md | 22 +++++++++++----------- README_ko.md | 22 +++++++++++----------- README_pl.md | 22 +++++++++++----------- README_pt-BR.md | 22 +++++++++++----------- README_ru.md | 22 +++++++++++----------- README_th.md | 22 +++++++++++----------- README_tr.md | 22 +++++++++++----------- README_uk.md | 22 +++++++++++----------- README_vi.md | 22 +++++++++++----------- README_zh-TW.md | 22 +++++++++++----------- README_zh.md | 22 +++++++++++----------- 17 files changed, 179 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index c8b64f36a..8f7fdf00c 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ REA launching its analysis bridge inside Hopper while inspecting a native binary -
+

@@ -337,6 +337,6 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and checks, ## License -[![Software license document with a check seal](docs/assets/rea-license.png)](LICENSE) - [MIT](LICENSE) + +[![Software license document with a check seal](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ar.md b/README_ar.md index df74422fe..24f145a0c 100644 --- a/README_ar.md +++ b/README_ar.md @@ -28,7 +28,7 @@ REA يشغّل جسر التحليل داخل Hopper لفحص ملف ثنائي للشيفرة الأصلية -
+

@@ -154,6 +154,8 @@ npx rea-agents@latest setup ## دراسات الحالة +[![رسوم توضيحية لأمثلة توزيع الصوت في DX-Ball وجسر الحافظة في Notion وحلقة الطلقات في TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: إعادة بناء حساب توزيع الصوت بين القناتين تتبّع استدعاء صوت إلى الدالة المساعدة التي تحوّل الموضع إلى توزيع بين القناتين، وافحص التعليمات، وحوّل الشيفرة شبه البرمجية غير المكتملة إلى C. تجتاز إعادة البناء 3,205 حالات اختبار على x86 الأصلي، وتعيد إنتاج جميع بايتات الدالة المترجمة البالغ عددها 63 بايتًا. @@ -254,16 +256,6 @@ npx rea-agents@latest setup أبلغ عن الثغرات وفق [SECURITY.md](SECURITY.md). -## المساهمة - -نرحّب بمساعدتك في تطوير REA! [افتح issue](https://github.com/morluto/rea/issues) للإبلاغ عن خطأ أو اقتراح ميزة، أو [أرسل pull request](https://github.com/morluto/rea/pulls) لتحسين الشيفرة أو التوثيق. - -راجع [CONTRIBUTING.md](CONTRIBUTING.md) لإعداد بيئة التطوير والفحوص، و[دليل الاختبار](docs/testing.md) لمسارات التحقق، و[خريطة البنية](docs/architecture.mermaid) لهيكل المشروع. - -## روابط المشروع - -[الموقع](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [الأمان](SECURITY.md) - ## سجل النجوم 🎉 **30,000 نجمة على GitHub — شكرًا لكم!** @@ -282,6 +274,14 @@ npx rea-agents@latest setup يوفّر REA أدوات لأبحاث الهندسة العكسية والتحليل وإعادة البناء المشروعة. أنت مسؤول عن الحصول على أي تفويض مطلوب والالتزام بالقوانين المعمول بها. لا يؤيد المشروع الاستخدام غير القانوني أو غير المصرّح به. +## المساهمة + +نرحّب بمساعدتك في تطوير REA! [افتح issue](https://github.com/morluto/rea/issues) للإبلاغ عن خطأ أو اقتراح ميزة، أو [أرسل pull request](https://github.com/morluto/rea/pulls) لتحسين الشيفرة أو التوثيق. + +راجع [CONTRIBUTING.md](CONTRIBUTING.md) لإعداد بيئة التطوير والفحوص، و[دليل الاختبار](docs/testing.md) لمسارات التحقق، و[خريطة البنية](docs/architecture.mermaid) لهيكل المشروع. + ## الترخيص [MIT](LICENSE) + +[![وثيقة ترخيص برمجيات مع ختم علامة صح](docs/assets/rea-license.png)](LICENSE) diff --git a/README_de.md b/README_de.md index 80dff4b31..45f47e3c0 100644 --- a/README_de.md +++ b/README_de.md @@ -28,7 +28,7 @@ REA startet seine Analysebrücke in Hopper und untersucht eine native Binärdatei -
+

@@ -154,6 +154,8 @@ Native Formate und unterstützte Hostsysteme unterscheiden sich je nach Provider ## Fallstudien +[![Illustrationen der Fallstudien zu DX-Balls Klangbalance, Notions Zwischenablage-Brücke und TH04s Geschossring](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: Eine Stereo-Panning-Berechnung rekonstruieren Verfolge einen Sound-Aufruf zur Hilfsfunktion, die Positionen in Panning-Werte umrechnet, untersuche die Anweisungen und überführe unvollständigen Pseudocode in C. Die Rekonstruktion besteht 3.205 Tests mit dem ursprünglichen x86-Code und reproduziert alle 63 Bytes der kompilierten Funktion. @@ -252,16 +254,6 @@ Beginne mit den [praxisnahen Anleitungen](https://rea.tools/guides/) auf der Web Melde Sicherheitslücken gemäß [SECURITY.md](SECURITY.md). -## Mitwirken - -Wir freuen uns über deine Hilfe bei REA! [Öffne ein Issue](https://github.com/morluto/rea/issues), um einen Fehler zu melden oder eine Funktion vorzuschlagen, oder [sende einen Pull Request](https://github.com/morluto/rea/pulls), um Code oder Dokumentation zu verbessern. - -Die Entwicklungsumgebung und Prüfungen beschreibt [CONTRIBUTING.md](CONTRIBUTING.md), die Verifikationspfade der [Testleitfaden](docs/testing.md) und die Projektstruktur die [Architekturübersicht](docs/architecture.mermaid). - -## Projektlinks - -[Website](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Sicherheit](SECURITY.md) - ## Sternverlauf 🎉 **30.000 GitHub-Sterne – vielen Dank!** @@ -280,6 +272,14 @@ Danke an alle, die REA nutzen, Fehler melden, Funktionswünsche äußern, Builds REA stellt Werkzeuge für rechtmäßige Reverse-Engineering-Forschung, Analyse und Rekonstruktion bereit. Du bist dafür verantwortlich, erforderliche Genehmigungen einzuholen und geltendes Recht einzuhalten. Das Projekt unterstützt keine rechtswidrige oder unbefugte Nutzung. +## Mitwirken + +Wir freuen uns über deine Hilfe bei REA! [Öffne ein Issue](https://github.com/morluto/rea/issues), um einen Fehler zu melden oder eine Funktion vorzuschlagen, oder [sende einen Pull Request](https://github.com/morluto/rea/pulls), um Code oder Dokumentation zu verbessern. + +Die Entwicklungsumgebung und Prüfungen beschreibt [CONTRIBUTING.md](CONTRIBUTING.md), die Verifikationspfade der [Testleitfaden](docs/testing.md) und die Projektstruktur die [Architekturübersicht](docs/architecture.mermaid). + ## Lizenz [MIT](LICENSE) + +[![Softwarelizenzdokument mit Prüfsiegel](docs/assets/rea-license.png)](LICENSE) diff --git a/README_es.md b/README_es.md index 02d81e836..3e8b2d433 100644 --- a/README_es.md +++ b/README_es.md @@ -28,7 +28,7 @@ REA inicia su puente de análisis dentro de Hopper mientras inspecciona un binario nativo -
+

@@ -154,6 +154,8 @@ Los formatos nativos y los sistemas anfitriones compatibles varían según el pr ## Casos prácticos +[![Ilustraciones de los casos de panoramización de sonido de DX-Ball, el puente del portapapeles de Notion y el anillo de proyectiles de TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: reconstruir un cálculo de panoramización de sonido Sigue una llamada de sonido hasta la función auxiliar que convierte la posición en panoramización, inspecciona las instrucciones y transforma el pseudocódigo incompleto en C. La reconstrucción supera 3.205 casos con el x86 original y reproduce los 63 bytes de la función compilada. @@ -252,16 +254,6 @@ Empieza con las [guías prácticas](https://rea.tools/guides/) del sitio web. Pa Informa de vulnerabilidades siguiendo [SECURITY.md](SECURITY.md). -## Contribuir - -¡Nos encantaría que ayudaras con REA! [Abre una issue](https://github.com/morluto/rea/issues) para comunicar un error o proponer una función, o [envía una pull request](https://github.com/morluto/rea/pulls) para mejorar el código o la documentación. - -Consulta [CONTRIBUTING.md](CONTRIBUTING.md) para preparar el entorno de desarrollo y las comprobaciones, la [guía de pruebas](docs/testing.md) para los procesos de verificación y el [mapa de arquitectura](docs/architecture.mermaid) para la estructura del proyecto. - -## Enlaces del proyecto - -[Sitio web](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Seguridad](SECURITY.md) - ## Historial de estrellas 🎉 **30.000 estrellas en GitHub: ¡gracias!** @@ -280,6 +272,14 @@ Gracias a quienes usan REA, informan de errores, solicitan funciones, prueban co REA proporciona herramientas para la investigación, el análisis y la reconstrucción mediante ingeniería inversa conforme a la ley. Eres responsable de obtener las autorizaciones necesarias y cumplir las leyes aplicables. El proyecto no respalda usos ilegales ni no autorizados. +## Contribuir + +¡Nos encantaría que ayudaras con REA! [Abre una issue](https://github.com/morluto/rea/issues) para comunicar un error o proponer una función, o [envía una pull request](https://github.com/morluto/rea/pulls) para mejorar el código o la documentación. + +Consulta [CONTRIBUTING.md](CONTRIBUTING.md) para preparar el entorno de desarrollo y las comprobaciones, la [guía de pruebas](docs/testing.md) para los procesos de verificación y el [mapa de arquitectura](docs/architecture.mermaid) para la estructura del proyecto. + ## Licencia [MIT](LICENSE) + +[![Documento de licencia de software con un sello de verificación](docs/assets/rea-license.png)](LICENSE) diff --git a/README_fa.md b/README_fa.md index 54918cef7..7ea5aee4e 100644 --- a/README_fa.md +++ b/README_fa.md @@ -28,7 +28,7 @@ اجرای پل تحلیل REA در Hopper هنگام بررسی یک فایل باینری بومی -
+

Discord
به انجمن مهندسی معکوس بپیوندید

دیسکورد · پرسش و پاسخ · نمایش دستاوردها
@@ -146,6 +146,8 @@ REA به Node.js 22.x (>=22.19)، 24.x (>=24.11) یا 26+، به‌همراه np ## نمونه‌های عملی +[![تصویرهایی از نمونه‌های پنینگ صدای DX-Ball، پل کلیپ‌بورد Notion و حلقهٔ گلوله‌های TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: بازسازی محاسبهٔ موقعیت استریوی صدا یک فراخوانی صوتی را تا تابع کمکی تبدیل موقعیت به pan دنبال کنید، دستورالعمل‌ها را بررسی کنید و شبه‌کد ناقص را به C تبدیل کنید. بازسازی حاصل، هر ۳٬۲۰۵ مورد آزمایش x86 اصلی را با موفقیت پشت سر می‌گذارد و هر ۶۳ بایت تابع کامپایل‌شده را دقیقاً بازتولید می‌کند. @@ -237,16 +239,6 @@ npx rea-agents@latest setup آسیب‌پذیری‌ها را از طریق [SECURITY.md](SECURITY.md) گزارش کنید. -## مشارکت - -از کمک شما به REA استقبال می‌کنیم! برای گزارش خطا یا پیشنهاد قابلیت، یک [issue باز کنید](https://github.com/morluto/rea/issues) یا برای بهبود کد و مستندات [pull request بفرستید](https://github.com/morluto/rea/pulls). - -برای راه‌اندازی محیط توسعه و بررسی‌ها، [CONTRIBUTING.md](CONTRIBUTING.md)، برای مراحل اعتبارسنجی [آزمایش‌ها](docs/testing.md) و برای ساختار پروژه [نقشهٔ معماری](docs/architecture.mermaid) را ببینید. - -## لینک‌های پروژه - -[وب‌سایت](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [امنیت](SECURITY.md) - ## تاریخچهٔ ستاره‌ها 🎉 **۳۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** @@ -259,8 +251,16 @@ npx rea-agents@latest setup REA ابزارهایی برای پژوهش، تحلیل و بازسازی قانونی در حوزهٔ مهندسی معکوس فراهم می‌کند. مسئولیت دریافت مجوزهای لازم و رعایت قوانین مربوط بر عهدهٔ شماست. این پروژه استفادهٔ غیرقانونی یا بدون مجوز را تأیید نمی‌کند. +## مشارکت + +از کمک شما به REA استقبال می‌کنیم! برای گزارش خطا یا پیشنهاد قابلیت، یک [issue باز کنید](https://github.com/morluto/rea/issues) یا برای بهبود کد و مستندات [pull request بفرستید](https://github.com/morluto/rea/pulls). + +برای راه‌اندازی محیط توسعه و بررسی‌ها، [CONTRIBUTING.md](CONTRIBUTING.md)، برای مراحل اعتبارسنجی [آزمایش‌ها](docs/testing.md) و برای ساختار پروژه [نقشهٔ معماری](docs/architecture.mermaid) را ببینید. + ## مجوز [MIT](LICENSE) +[![سند مجوز نرم‌افزار با مهر تأیید](docs/assets/rea-license.png)](LICENSE) + diff --git a/README_fr.md b/README_fr.md index 9dcd9ba39..0868d0543 100644 --- a/README_fr.md +++ b/README_fr.md @@ -28,7 +28,7 @@ REA lance son pont d'analyse dans Hopper pendant l'inspection d'un binaire natif -
+

@@ -155,6 +155,8 @@ Les formats natifs et les hôtes pris en charge varient selon le fournisseur. Co ## Études de cas +[![Illustrations des études sur la spatialisation sonore de DX-Ball, le pont du presse-papiers de Notion et le cercle de projectiles de TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball : reconstruire un calcul de panoramique sonore Suivez un appel sonore jusqu'à la fonction qui convertit une position en panoramique, inspectez ses instructions et transformez un pseudo-code incomplet en C. La reconstruction réussit 3 205 cas issus du x86 d'origine et reproduit à l'identique les 63 octets de la fonction compilée. @@ -253,16 +255,6 @@ Commencez par les [guides pas à pas](https://rea.tools/guides/) du site web. Po Signalez les vulnérabilités via [SECURITY.md](SECURITY.md). -## Contribuer - -Votre aide sur REA est la bienvenue ! [Ouvrez une issue](https://github.com/morluto/rea/issues) pour signaler un bug ou proposer une fonctionnalité, ou [envoyez une pull request](https://github.com/morluto/rea/pulls) pour améliorer le code ou la documentation. - -Consultez [CONTRIBUTING.md](CONTRIBUTING.md) pour l'environnement de développement et les vérifications, la page [tests](docs/testing.md) pour les filières de vérification, et la [carte de l'architecture](docs/architecture.mermaid) pour la structure du projet. - -## Liens du projet - -[Site web](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Sécurité](SECURITY.md) - ## Historique des étoiles 🎉 **30 000 étoiles GitHub — merci !** @@ -281,6 +273,14 @@ Merci à toutes les personnes qui utilisent REA, signalent des bugs, proposent d REA fournit des outils destinés à la recherche, à l'analyse et à la reconstruction légales en rétro-ingénierie. Il vous appartient d'obtenir toute autorisation nécessaire et de respecter les lois applicables. Le projet n'encourage aucune utilisation illégale ou non autorisée. +## Contribuer + +Votre aide sur REA est la bienvenue ! [Ouvrez une issue](https://github.com/morluto/rea/issues) pour signaler un bug ou proposer une fonctionnalité, ou [envoyez une pull request](https://github.com/morluto/rea/pulls) pour améliorer le code ou la documentation. + +Consultez [CONTRIBUTING.md](CONTRIBUTING.md) pour l'environnement de développement et les vérifications, la page [tests](docs/testing.md) pour les filières de vérification, et la [carte de l'architecture](docs/architecture.mermaid) pour la structure du projet. + ## Licence [MIT](LICENSE) + +[![Document de licence logicielle avec un sceau de validation](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ja.md b/README_ja.md index d3b2ffbe9..1412fc4ca 100644 --- a/README_ja.md +++ b/README_ja.md @@ -28,7 +28,7 @@ REA が Hopper 内で分析ブリッジを起動し、ネイティブバイナリを調べる様子 -
+

@@ -154,6 +154,8 @@ REA には Node.js 22.x(>=22.19)、24.x(>=24.11)、または 26+ と npm ## 事例 +[![DX-Ball の音声パン、Notion のクリップボードブリッジ、TH04 の弾幕リングの事例を表すイラスト](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball:音声のパン計算を再構築する 音声の呼び出しから位置をパンに変換する補助関数をたどり、命令を調べ、不完全な疑似コードを C に書き直します。再構築した実装は、元の x86 に対する 3,205 ケースの検証を通過し、コンパイル後の関数の全 63 バイトを再現しています。 @@ -254,16 +256,6 @@ npx rea-agents@latest setup 脆弱性の報告は [SECURITY.md](SECURITY.md) に従ってください。 -## 貢献する - -REA への貢献を歓迎します![issue を作成](https://github.com/morluto/rea/issues)してバグや機能の提案を報告したり、[pull request を送信](https://github.com/morluto/rea/pulls)してコードやドキュメントを改善したりできます。 - -開発環境とチェックは [CONTRIBUTING.md](CONTRIBUTING.md)、検証レーンは[テストガイド](docs/testing.md)、プロジェクト構造は[アーキテクチャ図](docs/architecture.mermaid)を参照してください。 - -## プロジェクトリンク - -[ウェブサイト](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [セキュリティ](SECURITY.md) - ## スター履歴 🎉 **GitHub スター 30,000 件、ありがとうございます!** @@ -282,6 +274,14 @@ REA の利用、バグ報告、機能の要望、ビルドのテスト、修正 REA は、合法的なリバースエンジニアリングの研究、分析、再構築のためのツールを提供します。必要な許可を得て、適用される法律に従う責任は利用者にあります。このプロジェクトは違法または無許可の利用を支持しません。 +## 貢献する + +REA への貢献を歓迎します![issue を作成](https://github.com/morluto/rea/issues)してバグや機能の提案を報告したり、[pull request を送信](https://github.com/morluto/rea/pulls)してコードやドキュメントを改善したりできます。 + +開発環境とチェックは [CONTRIBUTING.md](CONTRIBUTING.md)、検証レーンは[テストガイド](docs/testing.md)、プロジェクト構造は[アーキテクチャ図](docs/architecture.mermaid)を参照してください。 + ## ライセンス [MIT](LICENSE) + +[![チェックマークの印が付いたソフトウェアライセンス文書](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ko.md b/README_ko.md index efbc7f191..a5511cb02 100644 --- a/README_ko.md +++ b/README_ko.md @@ -28,7 +28,7 @@ REA가 Hopper 안에서 분석 브리지를 실행해 네이티브 바이너리를 검사하는 모습 -
+

@@ -154,6 +154,8 @@ REA에는 Node.js 22.x(>=22.19), 24.x(>=24.11) 또는 26+와 npm이 필요합니 ## 사례 +[![DX-Ball 사운드 패닝, Notion 클립보드 브리지, TH04 탄환 고리 사례를 보여 주는 그림](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: 사운드 패닝 계산 재구현 사운드 호출에서 위치를 패닝 값으로 변환하는 보조 함수까지 추적하고, 명령을 검사하여 불완전한 의사 코드를 C로 옮깁니다. 재구현한 코드는 원본 x86에 대한 3,205개 테스트 케이스를 통과했으며, 컴파일된 함수의 63바이트 전체를 재현합니다. @@ -254,16 +256,6 @@ npx rea-agents@latest setup 취약점은 [SECURITY.md](SECURITY.md)에 따라 보고하세요. -## 기여 - -REA에 도움을 보태 주세요! [issue를 등록](https://github.com/morluto/rea/issues)해 버그나 기능을 제안하거나, [pull request를 보내](https://github.com/morluto/rea/pulls) 코드와 문서를 개선할 수 있습니다. - -개발 환경과 검사 항목은 [CONTRIBUTING.md](CONTRIBUTING.md), 검증 절차는 [테스트 가이드](docs/testing.md), 프로젝트 구조는 [아키텍처 지도](docs/architecture.mermaid)를 참고하세요. - -## 프로젝트 링크 - -[웹사이트](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [보안](SECURITY.md) - ## 스타 기록 🎉 **GitHub 스타 30,000개, 감사합니다!** @@ -282,6 +274,14 @@ REA를 사용하고, 버그를 보고하고, 기능을 요청하고, 빌드를 REA는 합법적인 리버스 엔지니어링 연구, 분석, 재구성을 위한 도구를 제공합니다. 필요한 권한을 얻고 관련 법률을 준수할 책임은 사용자에게 있습니다. 이 프로젝트는 불법적이거나 허가받지 않은 사용을 지지하지 않습니다. +## 기여 + +REA에 도움을 보태 주세요! [issue를 등록](https://github.com/morluto/rea/issues)해 버그나 기능을 제안하거나, [pull request를 보내](https://github.com/morluto/rea/pulls) 코드와 문서를 개선할 수 있습니다. + +개발 환경과 검사 항목은 [CONTRIBUTING.md](CONTRIBUTING.md), 검증 절차는 [테스트 가이드](docs/testing.md), 프로젝트 구조는 [아키텍처 지도](docs/architecture.mermaid)를 참고하세요. + ## 라이선스 [MIT](LICENSE) + +[![확인 표시가 있는 소프트웨어 라이선스 문서](docs/assets/rea-license.png)](LICENSE) diff --git a/README_pl.md b/README_pl.md index 69a43b479..3be206acc 100644 --- a/README_pl.md +++ b/README_pl.md @@ -28,7 +28,7 @@ REA uruchamia most analityczny w Hopperze podczas analizy natywnego pliku binarnego -
+

@@ -154,6 +154,8 @@ Obsługiwane formaty natywne i platformy zależą od dostawcy analizy. Zobacz [k ## Przykłady zastosowań +[![Ilustracje studiów przypadku panoramowania dźwięku w DX-Ball, mostka schowka w Notion i pierścienia pocisków w TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: odtworzenie obliczania panoramy dźwięku Prześledź wywołanie dźwięku do funkcji pomocniczej przeliczającej pozycję na panoramę, sprawdź instrukcje i przekształć niepełny pseudokod w C. Odtworzona implementacja przechodzi 3 205 przypadków dla oryginalnego x86 i odtwarza wszystkie 63 bajty skompilowanej funkcji. @@ -252,16 +254,6 @@ Zacznij od [przewodników z przykładami](https://rea.tools/guides/) na stronie Zgłaszaj podatności zgodnie z [SECURITY.md](SECURITY.md). -## Współtworzenie - -Chętnie przyjmiemy Twoją pomoc w rozwoju REA! [Otwórz zgłoszenie](https://github.com/morluto/rea/issues), aby poinformować o błędzie lub zaproponować funkcję, albo [wyślij pull request](https://github.com/morluto/rea/pulls) z ulepszeniami kodu lub dokumentacji. - -Zobacz [CONTRIBUTING.md](CONTRIBUTING.md), aby poznać konfigurację środowiska programistycznego i kontrole, [testowanie](docs/testing.md), aby poznać ścieżki weryfikacji, oraz [mapę architektury](docs/architecture.mermaid), aby poznać strukturę projektu. - -## Linki projektu - -[Strona internetowa](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Zgłoszenia](https://github.com/morluto/rea/issues) · [Bezpieczeństwo](SECURITY.md) - ## Historia gwiazdek 🎉 **30 000 gwiazdek na GitHubie — dziękujemy!** @@ -280,6 +272,14 @@ Dziękujemy wszystkim, którzy używają REA, zgłaszają błędy, proponują no REA dostarcza narzędzia do zgodnych z prawem badań z zakresu inżynierii wstecznej, analizy i odtwarzania. Odpowiadasz za uzyskanie wymaganych zezwoleń i przestrzeganie obowiązującego prawa. Projekt nie popiera działań nielegalnych ani nieautoryzowanych. +## Współtworzenie + +Chętnie przyjmiemy Twoją pomoc w rozwoju REA! [Otwórz zgłoszenie](https://github.com/morluto/rea/issues), aby poinformować o błędzie lub zaproponować funkcję, albo [wyślij pull request](https://github.com/morluto/rea/pulls) z ulepszeniami kodu lub dokumentacji. + +Zobacz [CONTRIBUTING.md](CONTRIBUTING.md), aby poznać konfigurację środowiska programistycznego i kontrole, [testowanie](docs/testing.md), aby poznać ścieżki weryfikacji, oraz [mapę architektury](docs/architecture.mermaid), aby poznać strukturę projektu. + ## Licencja [MIT](LICENSE) + +[![Dokument licencji oprogramowania z pieczęcią potwierdzenia](docs/assets/rea-license.png)](LICENSE) diff --git a/README_pt-BR.md b/README_pt-BR.md index 47fe811a9..bdc6612ad 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -28,7 +28,7 @@ REA inicia sua ponte de análise dentro do Hopper enquanto inspeciona um binário nativo -
+

@@ -154,6 +154,8 @@ Os formatos nativos e os sistemas anfitriões compatíveis variam por provedor. ## Casos de uso +[![Ilustrações dos estudos de panoramização de áudio do DX-Ball, da ponte da área de transferência do Notion e do anel de projéteis do TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: reconstruir um cálculo de panorâmica de áudio Siga uma chamada de áudio até a função auxiliar que converte posição em panorâmica, inspecione as instruções e transforme pseudocódigo incompleto em C. A reconstrução passa em 3.205 casos com o x86 original e reproduz todos os 63 bytes da função compilada. @@ -252,16 +254,6 @@ Comece pelos [guias práticos](https://rea.tools/guides/) do site. Para opções Relate vulnerabilidades conforme [SECURITY.md](SECURITY.md). -## Contribuir - -Sua ajuda com o REA é bem-vinda! [Abra uma issue](https://github.com/morluto/rea/issues) para relatar um bug ou sugerir uma funcionalidade, ou [envie um pull request](https://github.com/morluto/rea/pulls) para melhorar o código ou a documentação. - -Consulte [CONTRIBUTING.md](CONTRIBUTING.md) para configurar o ambiente de desenvolvimento e as verificações, o [guia de testes](docs/testing.md) para os fluxos de verificação e o [mapa da arquitetura](docs/architecture.mermaid) para a estrutura do projeto. - -## Links do projeto - -[Site](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Segurança](SECURITY.md) - ## Histórico de estrelas 🎉 **30.000 estrelas no GitHub — muito obrigado!** @@ -280,6 +272,14 @@ Obrigado a todos que usam o REA, relatam bugs, sugerem funcionalidades, testam b O REA fornece ferramentas para pesquisa, análise e reconstrução por engenharia reversa dentro da lei. Você é responsável por obter as autorizações necessárias e cumprir as leis aplicáveis. O projeto não apoia usos ilegais ou não autorizados. +## Contribuir + +Sua ajuda com o REA é bem-vinda! [Abra uma issue](https://github.com/morluto/rea/issues) para relatar um bug ou sugerir uma funcionalidade, ou [envie um pull request](https://github.com/morluto/rea/pulls) para melhorar o código ou a documentação. + +Consulte [CONTRIBUTING.md](CONTRIBUTING.md) para configurar o ambiente de desenvolvimento e as verificações, o [guia de testes](docs/testing.md) para os fluxos de verificação e o [mapa da arquitetura](docs/architecture.mermaid) para a estrutura do projeto. + ## Licença [MIT](LICENSE) + +[![Documento de licença de software com selo de verificação](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ru.md b/README_ru.md index 216b868c5..e970b05b1 100644 --- a/README_ru.md +++ b/README_ru.md @@ -28,7 +28,7 @@ REA запускает мост анализа внутри Hopper при исследовании нативного бинарного файла -
+

@@ -154,6 +154,8 @@ REA требует Node.js 22.x (>=22.19), 24.x (>=24.11) или 26+, а так ## Примеры +[![Иллюстрации примеров панорамирования звука в DX-Ball, моста буфера обмена Notion и кольца пуль в TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: восстановление расчёта звуковой панорамы Проследите звуковой вызов до функции, преобразующей координату в значение панорамы, изучите инструкции и превратите неполный псевдокод в C. Восстановленная реализация проходит 3 205 тестов с исходным x86-кодом и воспроизводит все 63 байта скомпилированной функции. @@ -252,16 +254,6 @@ npx rea-agents@latest setup Сообщайте об уязвимостях согласно [SECURITY.md](SECURITY.md). -## Участие в проекте - -Будем рады вашей помощи с REA! [Откройте issue](https://github.com/morluto/rea/issues), чтобы сообщить об ошибке или предложить функцию, либо [отправьте pull request](https://github.com/morluto/rea/pulls) с улучшениями кода или документации. - -Настройка среды разработки и проверки описаны в [CONTRIBUTING.md](CONTRIBUTING.md), направления проверки — в [руководстве по тестированию](docs/testing.md), а структура проекта — на [схеме архитектуры](docs/architecture.mermaid). - -## Ссылки проекта - -[Сайт](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Безопасность](SECURITY.md) - ## История звёзд 🎉 **30 000 звёзд на GitHub — спасибо!** @@ -280,6 +272,14 @@ npx rea-agents@latest setup REA предоставляет инструменты для законных исследований, анализа и реконструкции с помощью реверс-инжиниринга. Вы отвечаете за получение необходимых разрешений и соблюдение применимых законов. Проект не поддерживает незаконное или несанкционированное использование. +## Участие в проекте + +Будем рады вашей помощи с REA! [Откройте issue](https://github.com/morluto/rea/issues), чтобы сообщить об ошибке или предложить функцию, либо [отправьте pull request](https://github.com/morluto/rea/pulls) с улучшениями кода или документации. + +Настройка среды разработки и проверки описаны в [CONTRIBUTING.md](CONTRIBUTING.md), направления проверки — в [руководстве по тестированию](docs/testing.md), а структура проекта — на [схеме архитектуры](docs/architecture.mermaid). + ## Лицензия [MIT](LICENSE) + +[![Документ лицензии на программное обеспечение с отметкой подтверждения](docs/assets/rea-license.png)](LICENSE) diff --git a/README_th.md b/README_th.md index f4d69f9f0..846c01bf2 100644 --- a/README_th.md +++ b/README_th.md @@ -28,7 +28,7 @@ REA เริ่มบริดจ์การวิเคราะห์ภายใน Hopper ขณะตรวจสอบไบนารีเนทีฟ -
+

@@ -154,6 +154,8 @@ REA ต้องใช้ Node.js 22.x (>=22.19), 24.x (>=24.11) หรือ 26 ## ตัวอย่างการใช้งาน +[![ภาพประกอบกรณีศึกษาการแพนเสียงใน DX-Ball บริดจ์คลิปบอร์ดของ Notion และวงแหวนกระสุนใน TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: สร้างการคำนวณแพนเสียงขึ้นใหม่ ติดตามการเรียกเสียงไปยังฟังก์ชันช่วยแปลงตำแหน่งเป็นค่าแพน ตรวจสอบคำสั่ง และแปลงโค้ดเทียมที่ยังไม่สมบูรณ์เป็น C การสร้างขึ้นใหม่นี้ผ่านการทดสอบ 3,205 กรณีเทียบกับ x86 ต้นฉบับ และสร้างไบต์ทั้ง 63 ไบต์ของฟังก์ชันที่คอมไพล์แล้วได้ตรงกัน @@ -252,16 +254,6 @@ npx rea-agents@latest setup รายงานช่องโหว่ผ่าน [SECURITY.md](SECURITY.md) -## การมีส่วนร่วม - -เรายินดีรับความช่วยเหลือในการพัฒนา REA! [เปิด issue](https://github.com/morluto/rea/issues) เพื่อรายงานบั๊กหรือเสนอฟีเจอร์ หรือ[ส่ง pull request](https://github.com/morluto/rea/pulls) เพื่อปรับปรุงโค้ดหรือเอกสาร - -ดู [CONTRIBUTING.md](CONTRIBUTING.md) สำหรับการตั้งค่าสภาพแวดล้อมพัฒนาและการตรวจสอบ ดู[การทดสอบ](docs/testing.md) สำหรับแนวทางการตรวจยืนยัน และ[แผนผังสถาปัตยกรรม](docs/architecture.mermaid) สำหรับโครงสร้างโปรเจกต์ - -## ลิงก์ของโปรเจกต์ - -[เว็บไซต์](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [ความปลอดภัย](SECURITY.md) - ## ประวัติดาว 🎉 **30,000 ดาวบน GitHub — ขอบคุณทุกคน!** @@ -280,6 +272,14 @@ npx rea-agents@latest setup REA มีเครื่องมือสำหรับการวิจัยวิศวกรรมย้อนกลับ การวิเคราะห์ และการสร้างขึ้นใหม่อย่างถูกกฎหมาย คุณมีหน้าที่ขออนุญาตตามที่จำเป็นและปฏิบัติตามกฎหมายที่เกี่ยวข้อง โปรเจกต์นี้ไม่สนับสนุนการใช้งานที่ผิดกฎหมายหรือไม่ได้รับอนุญาต +## การมีส่วนร่วม + +เรายินดีรับความช่วยเหลือในการพัฒนา REA! [เปิด issue](https://github.com/morluto/rea/issues) เพื่อรายงานบั๊กหรือเสนอฟีเจอร์ หรือ[ส่ง pull request](https://github.com/morluto/rea/pulls) เพื่อปรับปรุงโค้ดหรือเอกสาร + +ดู [CONTRIBUTING.md](CONTRIBUTING.md) สำหรับการตั้งค่าสภาพแวดล้อมพัฒนาและการตรวจสอบ ดู[การทดสอบ](docs/testing.md) สำหรับแนวทางการตรวจยืนยัน และ[แผนผังสถาปัตยกรรม](docs/architecture.mermaid) สำหรับโครงสร้างโปรเจกต์ + ## สัญญาอนุญาต [MIT](LICENSE) + +[![เอกสารสัญญาอนุญาตซอฟต์แวร์พร้อมตราเครื่องหมายถูก](docs/assets/rea-license.png)](LICENSE) diff --git a/README_tr.md b/README_tr.md index 46cc6a296..613026e12 100644 --- a/README_tr.md +++ b/README_tr.md @@ -28,7 +28,7 @@ REA, yerel bir ikili dosyayı incelerken Hopper içinde analiz köprüsünü başlatıyor -
+

@@ -154,6 +154,8 @@ Yerel makine kodu içeren ikili dosya biçimleri ve ana bilgisayar desteği sağ ## Örnek çalışmalar +[![DX-Ball ses kaydırma, Notion pano köprüsü ve TH04 mermi halkası örneklerinin çizimleri](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: Sesin stereo konumlandırma hesabını yeniden oluşturma Bir ses çağrısından konumu stereo konumlandırmaya dönüştüren yardımcı fonksiyona ilerleyin, talimatları inceleyin ve eksik sözde kodu C'ye dönüştürün. Yeniden oluşturulan kod, özgün x86 üzerinde 3.205 test durumunu geçer ve derlenmiş fonksiyonun 63 baytının tamamını yeniden üretir. @@ -252,16 +254,6 @@ Web sitesindeki [uygulamalı rehberlerden](https://rea.tools/guides/) başlayın Güvenlik açıklarını [SECURITY.md](SECURITY.md) üzerinden bildirin. -## Katkıda bulunma - -REA'ya katkınızı bekliyoruz! Hata bildirmek veya özellik önermek için bir [issue açın](https://github.com/morluto/rea/issues); kodu veya belgeleri geliştirmek için bir [pull request gönderin](https://github.com/morluto/rea/pulls). - -Geliştirme ortamı ve kontroller için [CONTRIBUTING.md](CONTRIBUTING.md), doğrulama süreçleri için [test rehberi](docs/testing.md) ve proje yapısı için [mimari harita](docs/architecture.mermaid) belgelerine bakın. - -## Proje bağlantıları - -[Web sitesi](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Güvenlik](SECURITY.md) - ## Yıldız geçmişi 🎉 **GitHub'da 30.000 yıldız — teşekkürler!** @@ -280,6 +272,14 @@ REA'yı kullanan, hata bildiren, özellik talep eden, derlemeleri test eden ve d REA, yasal tersine mühendislik araştırması, analizi ve yeniden oluşturma için araçlar sağlar. Gerekli izinleri almak ve geçerli yasalara uymak sizin sorumluluğunuzdadır. Proje yasa dışı veya yetkisiz kullanımı desteklemez. +## Katkıda bulunma + +REA'ya katkınızı bekliyoruz! Hata bildirmek veya özellik önermek için bir [issue açın](https://github.com/morluto/rea/issues); kodu veya belgeleri geliştirmek için bir [pull request gönderin](https://github.com/morluto/rea/pulls). + +Geliştirme ortamı ve kontroller için [CONTRIBUTING.md](CONTRIBUTING.md), doğrulama süreçleri için [test rehberi](docs/testing.md) ve proje yapısı için [mimari harita](docs/architecture.mermaid) belgelerine bakın. + ## Lisans [MIT](LICENSE) + +[![Onay işaretli yazılım lisansı belgesi](docs/assets/rea-license.png)](LICENSE) diff --git a/README_uk.md b/README_uk.md index e317153aa..e8327846c 100644 --- a/README_uk.md +++ b/README_uk.md @@ -28,7 +28,7 @@ REA запускає міст аналізу всередині Hopper під час дослідження нативного бінарного файла -
+

@@ -154,6 +154,8 @@ REA потребує Node.js 22.x (>=22.19), 24.x (>=24.11) або 26+, а та ## Приклади +[![Ілюстрації прикладів панорамування звуку в DX-Ball, мосту буфера обміну Notion та кільця куль у TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: відновлення розрахунку звукової панорами Простежте звуковий виклик до допоміжної функції, що перетворює координату на панорамування, перевірте інструкції та перетворіть неповний псевдокод на C. Відновлена реалізація проходить 3 205 тестів з оригінальним x86-кодом і відтворює всі 63 байти скомпільованої функції. @@ -252,16 +254,6 @@ npx rea-agents@latest setup Повідомляйте про вразливості згідно з [SECURITY.md](SECURITY.md). -## Участь у проєкті - -Будемо раді вашій допомозі з REA! [Відкрийте issue](https://github.com/morluto/rea/issues), щоб повідомити про помилку чи запропонувати функцію, або [надішліть pull request](https://github.com/morluto/rea/pulls) з поліпшеннями коду чи документації. - -Налаштування середовища розробки й перевірки описано в [CONTRIBUTING.md](CONTRIBUTING.md), шляхи верифікації — у [посібнику тестування](docs/testing.md), а структуру проєкту — на [схемі архітектури](docs/architecture.mermaid). - -## Посилання проєкту - -[Сайт](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Безпека](SECURITY.md) - ## Історія зірок 🎉 **30 000 зірок на GitHub — дякуємо!** @@ -280,6 +272,14 @@ npx rea-agents@latest setup REA надає інструменти для законних досліджень, аналізу й реконструкції за допомогою реверс-інжинірингу. Ви відповідаєте за отримання необхідних дозволів і дотримання застосовних законів. Проєкт не підтримує незаконне або несанкціоноване використання. +## Участь у проєкті + +Будемо раді вашій допомозі з REA! [Відкрийте issue](https://github.com/morluto/rea/issues), щоб повідомити про помилку чи запропонувати функцію, або [надішліть pull request](https://github.com/morluto/rea/pulls) з поліпшеннями коду чи документації. + +Налаштування середовища розробки й перевірки описано в [CONTRIBUTING.md](CONTRIBUTING.md), шляхи верифікації — у [посібнику тестування](docs/testing.md), а структуру проєкту — на [схемі архітектури](docs/architecture.mermaid). + ## Ліцензія [MIT](LICENSE) + +[![Документ ліцензії на програмне забезпечення з позначкою підтвердження](docs/assets/rea-license.png)](LICENSE) diff --git a/README_vi.md b/README_vi.md index dd97996b4..8a84bf803 100644 --- a/README_vi.md +++ b/README_vi.md @@ -28,7 +28,7 @@ REA khởi chạy cầu nối phân tích bên trong Hopper khi kiểm tra tệp nhị phân mã máy -
+

@@ -154,6 +154,8 @@ Kiểm tra tĩnh JavaScript và .NET đọc các tệp được cung cấp mà k ## Các nghiên cứu điển hình +[![Minh họa các ví dụ về cân bằng âm thanh DX-Ball, cầu nối bảng nhớ tạm Notion và vòng đạn TH04](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball: tái tạo phép tính phân bố âm thanh trái phải Lần theo lời gọi âm thanh đến hàm hỗ trợ chuyển vị trí thành giá trị phân bố âm thanh, kiểm tra các lệnh và chuyển mã giả chưa đầy đủ sang C. Bản tái tạo vượt qua 3.205 trường hợp kiểm thử với x86 gốc và tái tạo đủ 63 byte của hàm đã biên dịch. @@ -252,16 +254,6 @@ Bắt đầu với [hướng dẫn thực hành](https://rea.tools/guides/) trê Báo cáo lỗ hổng theo [SECURITY.md](SECURITY.md). -## Đóng góp - -Chúng tôi hoan nghênh bạn giúp phát triển REA! [Mở issue](https://github.com/morluto/rea/issues) để báo lỗi hoặc đề xuất tính năng, hoặc [gửi pull request](https://github.com/morluto/rea/pulls) để cải thiện mã hay tài liệu. - -Xem [CONTRIBUTING.md](CONTRIBUTING.md) về thiết lập môi trường phát triển và các bước kiểm tra, [hướng dẫn kiểm thử](docs/testing.md) về các luồng xác minh và [sơ đồ kiến trúc](docs/architecture.mermaid) về cấu trúc dự án. - -## Liên kết dự án - -[Trang web](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Bảo mật](SECURITY.md) - ## Lịch sử sao 🎉 **30.000 sao trên GitHub — xin cảm ơn!** @@ -280,6 +272,14 @@ Cảm ơn mọi người đã sử dụng REA, báo lỗi, đề xuất tính n REA cung cấp công cụ cho nghiên cứu dịch ngược, phân tích và tái tạo hợp pháp. Bạn có trách nhiệm có được các quyền cho phép cần thiết và tuân thủ luật áp dụng. Dự án không ủng hộ việc sử dụng trái pháp luật hoặc không được cho phép. +## Đóng góp + +Chúng tôi hoan nghênh bạn giúp phát triển REA! [Mở issue](https://github.com/morluto/rea/issues) để báo lỗi hoặc đề xuất tính năng, hoặc [gửi pull request](https://github.com/morluto/rea/pulls) để cải thiện mã hay tài liệu. + +Xem [CONTRIBUTING.md](CONTRIBUTING.md) về thiết lập môi trường phát triển và các bước kiểm tra, [hướng dẫn kiểm thử](docs/testing.md) về các luồng xác minh và [sơ đồ kiến trúc](docs/architecture.mermaid) về cấu trúc dự án. + ## Giấy phép [MIT](LICENSE) + +[![Tài liệu giấy phép phần mềm có dấu kiểm](docs/assets/rea-license.png)](LICENSE) diff --git a/README_zh-TW.md b/README_zh-TW.md index dd0a77847..26a19c637 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -28,7 +28,7 @@ REA 在 Hopper 中啟動分析橋,檢查原生二進位檔案 -
+

@@ -154,6 +154,8 @@ REA 需要 Node.js 22.x(>=22.19)、24.x(>=24.11)或 26+,以及 npm。 ## 案例 +[![DX-Ball 聲音平移、Notion 剪貼簿橋接與 TH04 彈幕環案例的插圖](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball:重建聲像計算 沿聲音呼叫追蹤到根據位置計算聲像的輔助函數,檢查指令,將不完整的偽程式碼轉為 C。重建結果通過了 3,205 個原始 x86 測試用例,並復現了編譯後函數的全部 63 個位元組。 @@ -254,16 +256,6 @@ npx rea-agents@latest setup 請按照 [SECURITY.md](SECURITY.md) 報告漏洞。 -## 參與貢獻 - -歡迎幫助改進 REA!你可以[提交 issue](https://github.com/morluto/rea/issues) 報告錯誤或建議功能,也可以[提交 pull request](https://github.com/morluto/rea/pulls) 改進程式碼或文件。 - -開發設定和檢查見 [CONTRIBUTING.md](CONTRIBUTING.md),驗證流程見[測試指南](docs/testing.md),專案結構見[架構圖](docs/architecture.mermaid)。 - -## 專案連結 - -[網站](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [安全](SECURITY.md) - ## Star 歷史 🎉 **GitHub Star 達到 30,000 個,感謝大家!** @@ -282,6 +274,14 @@ npx rea-agents@latest setup REA 為合法的逆向工程研究、分析和重建提供工具。你有責任取得所需授權並遵守適用法律。本專案不認同非法或未經授權的使用。 +## 參與貢獻 + +歡迎幫助改進 REA!你可以[提交 issue](https://github.com/morluto/rea/issues) 報告錯誤或建議功能,也可以[提交 pull request](https://github.com/morluto/rea/pulls) 改進程式碼或文件。 + +開發設定和檢查見 [CONTRIBUTING.md](CONTRIBUTING.md),驗證流程見[測試指南](docs/testing.md),專案結構見[架構圖](docs/architecture.mermaid)。 + ## 授權條款 [MIT](LICENSE) + +[![帶有勾選印章的軟體授權文件](docs/assets/rea-license.png)](LICENSE) diff --git a/README_zh.md b/README_zh.md index bda5b4cef..2bbfae534 100644 --- a/README_zh.md +++ b/README_zh.md @@ -28,7 +28,7 @@ REA 在 Hopper 中启动分析桥,检查原生二进制文件 -
+

@@ -154,6 +154,8 @@ REA 需要 Node.js 22.x(>=22.19)、24.x(>=24.11)或 26+,以及 npm。 ## 案例 +[![DX-Ball 声音平移、Notion 剪贴板桥接与 TH04 弹幕环案例的插图](docs/assets/rea-showcases.png)](https://rea.tools/showcase/) + ### DX-Ball:重建声像计算 沿声音调用追踪到根据位置计算声像的辅助函数,检查指令,将不完整的伪代码转为 C。重建结果通过了 3,205 个原始 x86 测试用例,并复现了编译后函数的全部 63 个字节。 @@ -254,16 +256,6 @@ npx rea-agents@latest setup 请按照 [SECURITY.md](SECURITY.md) 报告漏洞。 -## 参与贡献 - -欢迎帮助改进 REA!你可以[提交 issue](https://github.com/morluto/rea/issues) 报告错误或建议功能,也可以[提交 pull request](https://github.com/morluto/rea/pulls) 改进代码或文档。 - -开发设置和检查见 [CONTRIBUTING.md](CONTRIBUTING.md),验证流程见[测试指南](docs/testing.md),项目结构见[架构图](docs/architecture.mermaid)。 - -## 项目链接 - -[网站](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [安全](SECURITY.md) - ## Star 历史 🎉 **GitHub Star 达到 30,000 个,感谢大家!** @@ -282,6 +274,14 @@ npx rea-agents@latest setup REA 为合法的逆向工程研究、分析和重建提供工具。你有责任取得所需授权并遵守适用法律。项目不支持非法或未经授权的使用。 +## 参与贡献 + +欢迎帮助改进 REA!你可以[提交 issue](https://github.com/morluto/rea/issues) 报告错误或建议功能,也可以[提交 pull request](https://github.com/morluto/rea/pulls) 改进代码或文档。 + +开发设置和检查见 [CONTRIBUTING.md](CONTRIBUTING.md),验证流程见[测试指南](docs/testing.md),项目结构见[架构图](docs/architecture.mermaid)。 + ## 许可证 [MIT](LICENSE) + +[![带有勾选印章的软件许可文件](docs/assets/rea-license.png)](LICENSE) From 5d16be2a7185db8b70a5fcbc5f5e1be63297f2c8 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:09:08 -0700 Subject: [PATCH 004/189] test: share the client registration command to restore the jscpd gate (#1317) After #1301 merged, main's duplicated-line share rose to 2.503%, over jscpd's 2.5% threshold, so Static checks fail on every PR. The new OMP test repeated the dialect test's imports and npx registration command. Export that command from the shared client test fixture instead. Co-authored-by: Claude Opus 5.5 --- .../filesystem/clientConfigurationDialects.test.ts | 12 +++++------- .../filesystem/ompClientConfiguration.test.ts | 13 +++++-------- tests/fixtures/clientEnvironment.ts | 10 ++++++++++ 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/tests/boundary/filesystem/clientConfigurationDialects.test.ts b/tests/boundary/filesystem/clientConfigurationDialects.test.ts index 609291932..71d6512ec 100644 --- a/tests/boundary/filesystem/clientConfigurationDialects.test.ts +++ b/tests/boundary/filesystem/clientConfigurationDialects.test.ts @@ -11,14 +11,12 @@ import { supportedClients } from "../../../src/application/SupportedClients.js"; import { PRODUCT_IDENTITY } from "../../../src/identity.js"; import { isOwnedClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; +import { + clearClientLocationEnvironment, + NPX_REGISTRATION_COMMAND, +} from "../../fixtures/clientEnvironment.js"; -const command = [ - "npx", - "-y", - PRODUCT_IDENTITY.registrationPackageSpecifier, - "mcp", -] as const; +const command = NPX_REGISTRATION_COMMAND; beforeEach(clearClientLocationEnvironment); diff --git a/tests/boundary/filesystem/ompClientConfiguration.test.ts b/tests/boundary/filesystem/ompClientConfiguration.test.ts index 2815ec134..0f5aeb2cc 100644 --- a/tests/boundary/filesystem/ompClientConfiguration.test.ts +++ b/tests/boundary/filesystem/ompClientConfiguration.test.ts @@ -8,16 +8,13 @@ import { readClientRegistrationStatuses } from "../../../src/application/ClientR import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js"; import { supportedClients } from "../../../src/application/SupportedClients.js"; import { systemUninstallHost } from "../../../src/application/Uninstall.js"; -import { PRODUCT_IDENTITY } from "../../../src/identity.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; +import { + clearClientLocationEnvironment, + NPX_REGISTRATION_COMMAND, +} from "../../fixtures/clientEnvironment.js"; -const command = [ - "npx", - "-y", - PRODUCT_IDENTITY.registrationPackageSpecifier, - "mcp", -] as const; +const command = NPX_REGISTRATION_COMMAND; beforeEach(clearClientLocationEnvironment); afterEach(() => vi.unstubAllEnvs()); diff --git a/tests/fixtures/clientEnvironment.ts b/tests/fixtures/clientEnvironment.ts index f8657d25c..79961e49d 100644 --- a/tests/fixtures/clientEnvironment.ts +++ b/tests/fixtures/clientEnvironment.ts @@ -1,5 +1,15 @@ import { vi } from "vitest"; +import { PRODUCT_IDENTITY } from "../../src/identity.js"; + +/** The default npx registration command setup writes on POSIX hosts. */ +export const NPX_REGISTRATION_COMMAND = [ + "npx", + "-y", + PRODUCT_IDENTITY.registrationPackageSpecifier, + "mcp", +] as const; + /** Environment variables that redirect where supported clients keep config. */ export const CLIENT_LOCATION_ENVIRONMENT = [ "APPDATA", From e10f1f0901fa56fb4443837cf9528b31a12e140e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:09:19 +0800 Subject: [PATCH 005/189] docs: keep license sections text-only --- README.md | 2 -- README_ar.md | 2 -- README_de.md | 2 -- README_es.md | 2 -- README_fa.md | 2 -- README_fr.md | 2 -- README_ja.md | 2 -- README_ko.md | 2 -- README_pl.md | 2 -- README_pt-BR.md | 2 -- README_ru.md | 2 -- README_th.md | 2 -- README_tr.md | 2 -- README_uk.md | 2 -- README_vi.md | 2 -- README_zh-TW.md | 2 -- README_zh.md | 2 -- docs/assets/rea-license.png | Bin 5961 -> 0 bytes 18 files changed, 34 deletions(-) delete mode 100644 docs/assets/rea-license.png diff --git a/README.md b/README.md index 8f7fdf00c..3475d8155 100644 --- a/README.md +++ b/README.md @@ -338,5 +338,3 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and checks, ## License [MIT](LICENSE) - -[![Software license document with a check seal](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ar.md b/README_ar.md index 24f145a0c..f4dcbda85 100644 --- a/README_ar.md +++ b/README_ar.md @@ -283,5 +283,3 @@ npx rea-agents@latest setup ## الترخيص [MIT](LICENSE) - -[![وثيقة ترخيص برمجيات مع ختم علامة صح](docs/assets/rea-license.png)](LICENSE) diff --git a/README_de.md b/README_de.md index 45f47e3c0..6e74d0cba 100644 --- a/README_de.md +++ b/README_de.md @@ -281,5 +281,3 @@ Die Entwicklungsumgebung und Prüfungen beschreibt [CONTRIBUTING.md](CONTRIBUTIN ## Lizenz [MIT](LICENSE) - -[![Softwarelizenzdokument mit Prüfsiegel](docs/assets/rea-license.png)](LICENSE) diff --git a/README_es.md b/README_es.md index 3e8b2d433..db73301c1 100644 --- a/README_es.md +++ b/README_es.md @@ -281,5 +281,3 @@ Consulta [CONTRIBUTING.md](CONTRIBUTING.md) para preparar el entorno de desarrol ## Licencia [MIT](LICENSE) - -[![Documento de licencia de software con un sello de verificación](docs/assets/rea-license.png)](LICENSE) diff --git a/README_fa.md b/README_fa.md index 7ea5aee4e..fbf8bc086 100644 --- a/README_fa.md +++ b/README_fa.md @@ -261,6 +261,4 @@ REA ابزارهایی برای پژوهش، تحلیل و بازسازی قان [MIT](LICENSE) -[![سند مجوز نرم‌افزار با مهر تأیید](docs/assets/rea-license.png)](LICENSE) - diff --git a/README_fr.md b/README_fr.md index 0868d0543..0b01db697 100644 --- a/README_fr.md +++ b/README_fr.md @@ -282,5 +282,3 @@ Consultez [CONTRIBUTING.md](CONTRIBUTING.md) pour l'environnement de développem ## Licence [MIT](LICENSE) - -[![Document de licence logicielle avec un sceau de validation](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ja.md b/README_ja.md index 1412fc4ca..2bdb5eb23 100644 --- a/README_ja.md +++ b/README_ja.md @@ -283,5 +283,3 @@ REA への貢献を歓迎します![issue を作成](https://github.com/morlut ## ライセンス [MIT](LICENSE) - -[![チェックマークの印が付いたソフトウェアライセンス文書](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ko.md b/README_ko.md index a5511cb02..9ce82f8f8 100644 --- a/README_ko.md +++ b/README_ko.md @@ -283,5 +283,3 @@ REA에 도움을 보태 주세요! [issue를 등록](https://github.com/morluto/ ## 라이선스 [MIT](LICENSE) - -[![확인 표시가 있는 소프트웨어 라이선스 문서](docs/assets/rea-license.png)](LICENSE) diff --git a/README_pl.md b/README_pl.md index 3be206acc..54f5aeb64 100644 --- a/README_pl.md +++ b/README_pl.md @@ -281,5 +281,3 @@ Zobacz [CONTRIBUTING.md](CONTRIBUTING.md), aby poznać konfigurację środowiska ## Licencja [MIT](LICENSE) - -[![Dokument licencji oprogramowania z pieczęcią potwierdzenia](docs/assets/rea-license.png)](LICENSE) diff --git a/README_pt-BR.md b/README_pt-BR.md index bdc6612ad..1d3c627ca 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -281,5 +281,3 @@ Consulte [CONTRIBUTING.md](CONTRIBUTING.md) para configurar o ambiente de desenv ## Licença [MIT](LICENSE) - -[![Documento de licença de software com selo de verificação](docs/assets/rea-license.png)](LICENSE) diff --git a/README_ru.md b/README_ru.md index e970b05b1..f88603244 100644 --- a/README_ru.md +++ b/README_ru.md @@ -281,5 +281,3 @@ REA предоставляет инструменты для законных и ## Лицензия [MIT](LICENSE) - -[![Документ лицензии на программное обеспечение с отметкой подтверждения](docs/assets/rea-license.png)](LICENSE) diff --git a/README_th.md b/README_th.md index 846c01bf2..dcbcaee28 100644 --- a/README_th.md +++ b/README_th.md @@ -281,5 +281,3 @@ REA มีเครื่องมือสำหรับการวิจั ## สัญญาอนุญาต [MIT](LICENSE) - -[![เอกสารสัญญาอนุญาตซอฟต์แวร์พร้อมตราเครื่องหมายถูก](docs/assets/rea-license.png)](LICENSE) diff --git a/README_tr.md b/README_tr.md index 613026e12..b77512bed 100644 --- a/README_tr.md +++ b/README_tr.md @@ -281,5 +281,3 @@ Geliştirme ortamı ve kontroller için [CONTRIBUTING.md](CONTRIBUTING.md), doğ ## Lisans [MIT](LICENSE) - -[![Onay işaretli yazılım lisansı belgesi](docs/assets/rea-license.png)](LICENSE) diff --git a/README_uk.md b/README_uk.md index e8327846c..d9224f713 100644 --- a/README_uk.md +++ b/README_uk.md @@ -281,5 +281,3 @@ REA надає інструменти для законних досліджен ## Ліцензія [MIT](LICENSE) - -[![Документ ліцензії на програмне забезпечення з позначкою підтвердження](docs/assets/rea-license.png)](LICENSE) diff --git a/README_vi.md b/README_vi.md index 8a84bf803..7004fe5da 100644 --- a/README_vi.md +++ b/README_vi.md @@ -281,5 +281,3 @@ Xem [CONTRIBUTING.md](CONTRIBUTING.md) về thiết lập môi trường phát t ## Giấy phép [MIT](LICENSE) - -[![Tài liệu giấy phép phần mềm có dấu kiểm](docs/assets/rea-license.png)](LICENSE) diff --git a/README_zh-TW.md b/README_zh-TW.md index 26a19c637..e5b6275bf 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -283,5 +283,3 @@ REA 為合法的逆向工程研究、分析和重建提供工具。你有責任 ## 授權條款 [MIT](LICENSE) - -[![帶有勾選印章的軟體授權文件](docs/assets/rea-license.png)](LICENSE) diff --git a/README_zh.md b/README_zh.md index 2bbfae534..3d7034742 100644 --- a/README_zh.md +++ b/README_zh.md @@ -283,5 +283,3 @@ REA 为合法的逆向工程研究、分析和重建提供工具。你有责任 ## 许可证 [MIT](LICENSE) - -[![带有勾选印章的软件许可文件](docs/assets/rea-license.png)](LICENSE) diff --git a/docs/assets/rea-license.png b/docs/assets/rea-license.png deleted file mode 100644 index 9870754e4e8db4862d67366f4432f02b36dac274..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5961 zcmV-P7q;k$P)004Lh0{{R3LVO8b00048P)t-s_4W7m z_W1Yr`S8bs{7yCMYc)ASL7D(e8QC2D~Gkbl4 zet?F7frf*Gif3tUE-*HYj*>1hIGvuNpP-|nqNTL7xRR2VM@ddwU}%Yoj*pO(m6e%? zh>TleY-DS7+}+{W*xDs2GFM(`UuSZ`!o|J5!G3~>hl-H+`1iWHz77*0A0{(>e~9do zU9em%wnY_sJtIt5YuQ^N_*ez;WDudAp&lYD-r(cN&DP1$*UZw|ny0xLJZUFMbR|Y| zEKGGRPI+g2n!CczGg5djP_dzFij9zkxn!OOM2%OfT+yv5NkPLRY$Po_HCTgdfSyroj(3Zt^_|2~00001Z*opl0neg$ng9S5 zn@L1LRCwC0T!~u~$+oZRbX6yWEr21=0c1%K5u-qq<*9?S+->g7xLgG%<~ox>8FAsw z`~Sc1Rn@8GRCOm|zV9A1>1>@}pHpW)6+#H1j-sd#1Ib6|wL&Cs;c4}PBFYFC#MBW< zl0-h2NK(&Bf=5I=p*~B!sIkhzj~`5{5cZU(N`NA{xbUWC0q~5}-mD zbMb(Q_rmAo5s%^A3ZFulV1(vjLYM{!ZzfE=DDD{?t4Fa9kW&qi$H0_`67>{S@R;J6 z*a)mJ3nOqsrLLk5?@LnLxwpy93MA3(DY>?r_XLtlyLq=IWfa)_Wvj7CP$f+=sXJkIlLVTPHEbc^1Diy=(?*TM#$^euM4FD4F zGoG-exG7VYgrpn51AMVmE<$roV>w9d)ezt^T3<%Iu@Xh>;jy3b&Ky(w84XbJ&#pjg zVF;Bkxpz{+eS`rw0G7QvY$NR&L}KP{$$G>AAcv1I1JJ1mGkO7+M=d}`vhwf&dh9p& zA`ou|pk4h;>K`}eRPb4w8}UKL3 z_F}QVIXD$=uY-laGWcLMSd~pkfG}qr<2A^^Rj366RzQfdU@zVSXqj&=BwPa)DG!|s z@k}^ckAOYkq}FF70i-fgwF?CckRyN&Py%))=fd6Bi=zQHD3Qj-gc(XniDIn9X)I2m zfH;HfP81^r&jmPuJ!gts~kH)R5F{ zHWxP+%T;kLx0XwlK`TE_M5TaB$r!NN3M-6;(KsPhLL?(tYhCKw>MX2$twFPt@|GAYfhx9-)}R_|}^ZUODJ zTKkF?7SxS~EzmaC+fxeQjn&yoPH09VDN3FCaDy=RJw+@7e-e8Dm9rx_zP76&Datz;QUwdalGk~0wvqsWg**F{zIirtioA88mV zN!!CEz}CI$+VTH19>t@q;I;&~cKl$qmaa`Kl=9sg(Z&Ql!9f)mg6db54Myp&Gv=jt-f42*L?S`sO>)|sfo2jP^y zCWy3@sTLx394w9oI0*ood&kwa+Vt!)9pIi_ScCw=y?`auNGg&zDmZ*zjoKWT3)Zd@DSec)i@NwZw7 z-`EL0=86u+yG5$hqB*ISS>ymRtL~X|fRdaTCAl8JscQXpdA;3iD_UP&s@FG587&s4 zrm;&KWg$awFtPw`)E8TOl&@&=@J|73i(p|X-LzrP{iU=z@$`@cd5B6^kq1V8*QF&~ zR^FHn7zdbwBq@{*oBQM6es}!v`)hHqTuU=_W4lz;DIRc8*$WoNQ-Xy$TxH4t3a3oD zQH6Yf;^2oLe)!7|fBEa*{(c<}?yt8OHzA&JBwUIDr~_&UWOOncXA)Nq?|}r_nU{P+ zDv$s1qo9BO_}6Oze7eE{o}`f z3c4P^V(HOtv#~zs(fVdb08DV@$N@wQ|MENI#aZoSyYwy*bew+}>^|fN*AK ze3_2yTnX1zQ*qaUaOORSqZtKo;a~gf{~52rnYw~7d%7O}k_%o%6wYzf{l*01(UEq*$7ckJ#?W9we+=)uE{N0HNFL8X%X zKY&iM0CA*g;wb%#17!7a4VmKeG4!dfX{S}p%-CWwl+F6t#Er1Rb++LA##$&o))nJNJ_&A zl&4?;-f?TtR#mlfA}?lIFQ~>QqH9~rXMTsD%A}sbldAk?04g(MO$peUpFR3b-Te0R z3jc&?Ssx1;_1UzOLtfn2o3;Qe!cf2VDX`R%q^kp^2?4s4QKZEx zC1N2!l?ebB<@b|Jf7?ZB#1xM-2Zh{LN-tma&d$!e-JYViXK#CF>OlPU-YT~z9-Y29 z$>$)nc5G@KtVEER4Y#-lFbSJKp#GABKEQXcUXLQ_>Q+2}#X-d*523y z2-^b~sWtf9v)_i3^n}m7HF)Pb09}<_n>Zc8vK)k_k|bUYIH+Bn(^z|J9|3s)x32+^ zIcAw&j++z;0V3BT06y8n989#o3oRZzvr?%@FKF>VxOEMH-YkQYHg_QwB|(EyXc+($ z9F)<_h6ecO4D}!m(jb!H z79ffRjUH1o)S_$DQpCTgU|~g-(N|WA9t{VWrzFr2l=%nCn-X!B#MqT2Gk_!2iXni& z!F*RY93V0?cBo615~5(XE(ajXY4^J%o7yVBQ<4`iZ@vV&Y3cp@K`g8+?61q}RuTd< zwT@u;j}EetlFzYzr>DrO%CEGzDFIeWAO3yu?%l=3g*3<)#xnQ(o{eqoR4R|3E~Ha; zOJ0N978gWDqT+f+Mv`nZtL_A2#Gh6y7(3XMzPKn|-TB*IK)+*v#lqaw_{8L-Y{HLE zEsjlW&%~(4Z+NI;{TL0Pk#LeD0M4XH<&uR862kyxPSTJ7r7!Nv^!KC8J$3eZe(D2^ zR=@33JJo7O(ERk>orPynUhu693!?=*KIH@S;4w81X4>`gvcTENh}v;5NtR!{c>Y|L z6rLLrM=wk$TR9nEiRn#g|WC`)Mbw`2Y#__f9jY)f1X^gFKFntARjO4YguX@w3PO%i#y96KD!KI8Wu`j23CxYQFl`Zi_Dg{ zOu&jcI5HDMn`KAM2>%a^p%pRYX+c&L+1u0jNgXEpN#%<$Ag&}i~P{!suA zXByR`e&@0WL9F6p@9TG+etLJgnCTtI)U$JRn2~`VeBQcrc2MUeL;P-OyVmb_(u*(W zXXg&!)t62uO~;r0q0PkaDN3=1gA*Bms?X?H4)K@^`5U7ElG6VCQF?iC-aGFad~aW! zUG=_Prk$w-8*3fPQ#S_5^n@P6Ssb1tl<$sFq+`d~48XAPK3CJ*+fOsIrLim2n9dz#-tfAa`lhZO;TiEi1#o%&-c;J}f9eW+ z=jU3!A4<19_Kn6B`CXJ@^$tCusSn}5h;Q~;d6w_9;AXHrAR;6~ON4AMe?V55Eif{`$L+w$$g33ZN?sh*L+IIpG`_%qy!qsAwD+ z11#imkApoYV|xHlu<%vyMN;{YB)`6S-976nZSJQUph+efI>%v*1jl-MC$JsUFGtwPA>$&dquoehY`ZbfJ~X%tqKeQK4Ce)+w3uK3rx`c&6}y(@y1!+s#H({gdOMFcNATuY$Jr+FOgllbrS-mO1U(+(iKF zl%Fq~oSS>O29CjWoI~+AmzHm^)kGIRTz#-!FT?cZ-j*eC*lO+VwOVQ-v(;*Uvnc=` zT?Pr&)#+Ce;!IT{7b%eZqM8ZBbS?^sslRJLb{7jCAC;1f*V3gmGg|A7*ed#dL(yDw zvnusO`jW2HW}xmD5pC7V%l;M_PsrNd7(vGr@i5%hKzM-$0NbtOaycDI_3HH8{mJy` z=;-rR*96o;p}!vW)3w#jiqlyZ6ef*5v{8iHKNstcnLotBJ%ESbY;7$F-sBBVFUfi8 zCH+cma=p1)U8~nGKYh7U3>5!Aed^cy^HW8dt<7Y%r`bA|-r0vn&Vwl%%52~$0Je8` zTZ?PuTR^vO-xfFG4`@w3aeGbNmDg6=8ym-xm+9r@=POB{E`@m0>T0tRs4I)2m=cz0 zRqMiy-q=T@nCAk7@fGlmrGxFA)?RCC*N{>WeYCr4RYt1H!v6L~xxCgtO4FmylKM;i ze!YCFc{c+PCbn2M2tc!2XmTdIb;Wc*)rYnlyX|IRRt)XJ?Jj7wQ0DE;T3swVSeN~! z`LwycoSA=PFsr3Q`!ERP8Gtai8Ulo{L&bWzHaaxePals7MlP(cPA#Rf?9mao6Vub} z?aUOW@?kX2gjY6(kvXXbs4*&T$IjfictIc(zN`RKrD`{=q{xwWekUiSG_$iKOybVw z(d}DeS&Fr~))*Vx8LQ;C9w~ATUaOkwOxbx3X16Q}Gvkf5Qf7Vn$Z{%7!0qm}v^C!o zX1#ec$qdaCJJ%nw5LTrw1Dd)a%kEc=@h&CR4!=IlK9X{7fq!Y;eEQ7JE1`XFwyPS4 z!i{aA)z&r9=7}IYl>E$Z0}ttC^U|{gyH#T6u;e?Cf!zo_F$0^|%uZ~U@rMMBt~h|n z^#GbT7F~hWTMs1IzUuRiGds)>Y0<-sYFJdn6KY&-LA)kDx7o`LR%dpB8d>GU(J^-! zCe3U?&1`lZ`1;`7c*J{cggU59j_Ul(0%St~jvSdFByTEr$o{nv-A=!lINK7GN|!x2t>r1Mw_aF2F*8 zdcmQaqGv=mcrsmgLUN^>H+aFqp9&zvcW172U_=!BEJ0+nl@Fc~;M@$=>g(l%3|!UB z8!ibJ0zrHu0b_HvtbkGRG9VhnUXY5A1nEnXGnnp`){!9##+&h$XRmLlFG=I$X5XKl zaLQU3)MkL-IU&fc1cT`V?G=UX!h@Kd1bf=u5Jw!3ZXCMpI&#YpCul&_xpcj7D8W5k zW?G{*+D!&e*=I&3m7k}hJDXNUJdT4+Yk1Qy{BR3XEJC#|83}(!BySPtm_Nf+ToKKSuNYyOl?TdgwKEC!5*vheG|n4!V40~4KQ<-d z3@@sPj*PEtmn8U!A~cZBY=^=H{2XV^xxd>%a(?JRox<#?Qa3*P*nkTr@S7~01o)tV zXxd~v^Ghr?ss%F<2eX)--2n3NT rG0Lcy*m%F|Vt!9W17xl=WDx#8XUVq`1d+T800000NkvXXu0mjf$vHN@ From a64851f2592cd353600d54864b38524705341dd1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:17:20 +0000 Subject: [PATCH 006/189] chore(release/6.2.0): release rea-agents 6.2.0 (#1305) * chore(release/6.2.0): release rea-agents 6.2.0 * docs(release): complete 6.2 breaking migration notes * fix(dev): allow formatter-ignored staged files * docs(release): include all unreleased mainline entries * docs(release): note ignored-file hook repair --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: N0zoM1z0 <1705004398@qq.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 243 ++++++++++++++++++++++++++++++++ docs/installation.md | 2 +- docs/migration-6.2.md | 7 + package-lock.json | 4 +- package.json | 4 +- server.json | 4 +- src/generatedPackageMetadata.ts | 2 +- 8 files changed, 259 insertions(+), 9 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8ace91523..e1e352c16 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "6.1.0" + ".": "6.2.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 7751685d4..0bd5ae5cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,248 @@ # Changelog +## [6.2.0](https://github.com/morluto/rea/compare/rea-agents-6.1.0...rea-agents-6.2.0) (2026-10-09) + + +### ⚠ BREAKING CHANGES + +Read the [6.1 to 6.2 migration guide](docs/migration-6.2.md) before upgrading. REA's `always-bump-minor` policy includes breaking changes; 6.2 is not a backward-compatibility promise. Preserve original saved files and regenerate missing observations rather than fabricating identities or facts. + +* **MCP / Evidence / snapshots / artifacts:** Success results are direct canonical Evidence; read `normalized_result` rather than the old `result`/`evidence` wrapper. Evidence requires nullable `analysis_profile`, session provider aliases are removed, snapshots require complete profile-bound query records, and artifact roles/permissions belong to occurrences. Recreate incompatible saved data; adding fields without recomputing their semantic identity is invalid. ([63bf914](https://github.com/morluto/rea/commit/63bf91405cf97b114a84f337fb1272d98a267999)) +* **Process captures:** Legacy v3 conversion is removed. Explicit executable identity and `event_journal` are required; retain old captures and recapture when current comparisons are needed instead of inventing launch identity or event order. ([2a77469](https://github.com/morluto/rea/commit/2a7746998d47446c4db6d4f524e0f183d6803f3f)) +* **Cleanup and evaluation:** A one-shot analysis reports cleanup failure while preserving the completed observation or primary diagnostic. Handle `cleanup_incomplete` and retained observations/resources. Configured agent-evaluation fixtures require Evidence-backed correctness, not routing or answer wording alone. ([#1211](https://github.com/morluto/rea/pull/1211), [27a9cea](https://github.com/morluto/rea/commit/27a9ceade7232c1c9a24dc7d454ae060948183a1)) +* **JavaScript:** Return-field projections require explicit presence; export-shape changes carry both sides' presence and property inventory coverage. Semantic object operations retain complete `property_path` segments. Regenerate old analysis and distinguish unknown values from unknown presence. ([475a0f8](https://github.com/morluto/rea/commit/475a0f84dac63d710e032bc7f731c1a3bda624ec)) +* **Function comparisons:** Remove the unreachable `truncated` dimension state and `summary.truncated` counter; update enum and display consumers while retaining explicit `unknown` facts. ([5510b27](https://github.com/morluto/rea/commit/5510b27d7f863a3df26212fba4a59f8df0da3712)) +* **Historical sources:** Unreadable/unknown symlink targets require `target: null`; external targets retain the observed absolute target. Reimport graphs containing display placeholders such as `` and handle nullable targets. ([b7b4333](https://github.com/morluto/rea/commit/b7b433370310c3ffe33d5027d8393151d5e862da)) + +### Features + +* **javascript:** report observed export property presence ([#1160](https://github.com/morluto/rea/issues/1160)) ([45e3edc](https://github.com/morluto/rea/commit/45e3edc17f48954c89d8db86f7313c479bd39344)) +* **mcp:** select views of retained analysis results ([#1180](https://github.com/morluto/rea/issues/1180)) ([db675f1](https://github.com/morluto/rea/commit/db675f1d52acda62b6f57b5a8773532f49b259e7)) +* **website:** add an Aegis APK code-generation showcase ([0270dd5](https://github.com/morluto/rea/commit/0270dd5739480acced62e045b5890ec0ebde2631)) +* **website:** add an Android showcase and clearer project prompts ([6cc817e](https://github.com/morluto/rea/commit/6cc817e8bd377b064b3568ef1eacb27eaefcb4c1)) +* **website:** add beginner examples and synchronized publishing ([0fec65d](https://github.com/morluto/rea/commit/0fec65d06b2f5431e704c472e53015d4b3cc967c)) +* **website:** add beginner examples and synchronized publishing ([#1203](https://github.com/morluto/rea/issues/1203)) ([0fec65d](https://github.com/morluto/rea/commit/0fec65d06b2f5431e704c472e53015d4b3cc967c)) +* **website:** add Discord link beside GitHub badge ([cc39fc5](https://github.com/morluto/rea/commit/cc39fc53b829a349ae199823472990a53014c507)) +* **website:** add homepage navigation and faster reading paths ([863674b](https://github.com/morluto/rea/commit/863674b2e92dd7c699768db82d521ccc88b7ebe4)) +* **website:** add homepage navigation and faster reading paths ([c94f06d](https://github.com/morluto/rea/commit/c94f06d98f895eb8b6c5ffa5e999ef1d4bb5eea2)) +* **website:** add homepage navigation and faster reading paths ([#1213](https://github.com/morluto/rea/issues/1213)) ([863674b](https://github.com/morluto/rea/commit/863674b2e92dd7c699768db82d521ccc88b7ebe4)) +* **website:** add search metadata and automatic sitemap ([99f257b](https://github.com/morluto/rea/commit/99f257bbf03c27327e5e0a232fefd3c792acd5bc)) +* **website:** add search metadata and automatic sitemap ([b8851cb](https://github.com/morluto/rea/commit/b8851cb977cfdd608798d32bf5877f645b960831)), closes [#1283](https://github.com/morluto/rea/issues/1283) +* **website:** clarify reverse engineering and showcase goals ([e750c26](https://github.com/morluto/rea/commit/e750c262fbf37100369ab25bf8659daa1a2c4cc7)) +* **website:** explain REA through a first investigation ([5160d9b](https://github.com/morluto/rea/commit/5160d9b717d0207a357c754bdf72e215e59d19d1)) +* **website:** explain REA with Calculator and a playable dinosaur lab ([11b9f03](https://github.com/morluto/rea/commit/11b9f0346cf5413045b41ff552a024e11ba46ccc)) +* **website:** lead with the playable dinosaur example ([19c52f5](https://github.com/morluto/rea/commit/19c52f5e3f42fb754fc154bbd16552c5111df0c5)) +* **website:** show manual analysis beside a one-prompt workflow ([291bc6f](https://github.com/morluto/rea/commit/291bc6fb70f47d28d23440f03a8a7fa49eb9a391)) + + +### Bug Fixes + +* **dev:** accept formatter-ignored staged documentation without failing the commit hook; malformed JSON remains rejected. ([bd2db2f](https://github.com/morluto/rea/commit/bd2db2f0fa495fb08dea443cd16d7683d4b86e6a)) + +* **release:** publish reviewed release-PR merges from their exact reviewed source. ([c12bad7](https://github.com/morluto/rea/commit/c12bad7f139431fc0db7a8b7c9db1eab95f96dc2)) + +* **android:** support owned JADX stdio on Windows ([#1276](https://github.com/morluto/rea/issues/1276)) ([636b245](https://github.com/morluto/rea/commit/636b245f1badf2a7ecfa63c6e2378ac2f7673cc3)), closes [#1262](https://github.com/morluto/rea/issues/1262) +* **android:** validate engine archive prerequisites ([#1145](https://github.com/morluto/rea/issues/1145)) ([e9ebfb9](https://github.com/morluto/rea/commit/e9ebfb94eff0699b1ea84bba000c4467fa1cb998)) +* **apple:** report unusable dylib-resolution roots as invalid input ([6a1e558](https://github.com/morluto/rea/commit/6a1e558db3ec2b69561e91ea817f1c2065dfc676)) +* **apple:** report unusable dylib-resolution roots as invalid input ([24a30fd](https://github.com/morluto/rea/commit/24a30fd91c144b7f2533e5f5de8c91268773519c)) +* **artifacts:** keep cancellation and the caller path in extraction refusals ([37025cc](https://github.com/morluto/rea/commit/37025cc09f12d49f46e61eedc3564c710089146b)) +* **artifacts:** keep cancellation and the caller path in extraction refusals ([eacf846](https://github.com/morluto/rea/commit/eacf8461dad6bab11a3d5438e6db001a10f33a9b)) +* **artifacts:** match lipo arm64e variant names to their FAT slices ([de5bfec](https://github.com/morluto/rea/commit/de5bfec79fe862816350b2deeb42a12c0734d855)) +* **artifacts:** match lipo arm64e variant names to their FAT slices ([0b32577](https://github.com/morluto/rea/commit/0b32577a90aef97e36adf2a7af4f3eccd5d82357)), closes [#1168](https://github.com/morluto/rea/issues/1168) +* **artifacts:** name only host-available workflows for non-archive plists ([f4c99ab](https://github.com/morluto/rea/commit/f4c99ab8a53806dd57dc24b3d5a600905bcb4686)) +* **artifacts:** name only host-available workflows for non-archive plists ([2295855](https://github.com/morluto/rea/commit/22958558eafdfccf71a7d5bbbcf360574a6b2e3c)) +* **artifacts:** recheck failed DMG detaches before reporting cleanup failure ([#1155](https://github.com/morluto/rea/issues/1155)) ([58a91f0](https://github.com/morluto/rea/commit/58a91f03d72162849991caf537ab058ccc918594)) +* **artifacts:** refuse unsupported extraction formats before scanning ([8e74c9c](https://github.com/morluto/rea/commit/8e74c9c62fb44556b90f20bb6c12771ac05a18f2)) +* **artifacts:** report encrypted archive entries as unsupported extraction ([de43da7](https://github.com/morluto/rea/commit/de43da71ae982dd0f3d7b5ae49c914729db3a6ec)) +* **artifacts:** report non-archive keyed-archive selections as unsupported targets ([fef38e4](https://github.com/morluto/rea/commit/fef38e4d22ee859ec43fb591d53e8b9973c69958)) +* **artifacts:** report non-archive keyed-archive selections as unsupported targets ([8c5088c](https://github.com/morluto/rea/commit/8c5088c8cdf32a9f96f6c479c6e70a71fa360168)) +* **artifacts:** report wrong target kinds as unsupported targets ([b34bdcd](https://github.com/morluto/rea/commit/b34bdcdb2877be394c59c9cbf70269dc1841ff78)) +* **artifacts:** report wrong target kinds as unsupported targets ([637bcb5](https://github.com/morluto/rea/commit/637bcb5e4182b6c60e922b18688642d8e1008e90)) +* **browser:** classify export-web-scripts capture selection failures by cause ([ddaa183](https://github.com/morluto/rea/commit/ddaa18301ab9c67e7a6f7ce66076075e8a4d5017)) +* **browser:** classify export-web-scripts capture selection failures by cause ([8c5e34c](https://github.com/morluto/rea/commit/8c5e34cd379392ca40f651ca5eeb6a947b44aa33)) +* **browser:** report Windows HAR heap exhaustion ([#1147](https://github.com/morluto/rea/issues/1147)) ([1393507](https://github.com/morluto/rea/commit/13935077ba039f6e342f9c11ab5eea935a335ae6)) +* **browser:** retain scenario observations across failures ([614e0c2](https://github.com/morluto/rea/commit/614e0c2e74819bb5e3ef3d2e16ff31ee6cab76ae)) +* **browser:** retain scenario resources until cleanup succeeds ([88640f6](https://github.com/morluto/rea/commit/88640f60fe566edbe2320688df62c7ef46c4c61c)) +* **ci:** pass selected environment to Windows Ghidra fixture ([#1281](https://github.com/morluto/rea/issues/1281)) ([f085589](https://github.com/morluto/rea/commit/f085589957922eaf421db814399e88e415712050)) +* **cli:** advertise defaulted inputs as optional in --schema and help ([#1175](https://github.com/morluto/rea/issues/1175)) ([b4927a0](https://github.com/morluto/rea/commit/b4927a0a4fa7e8935b101d214b396bfa78208281)), closes [#1169](https://github.com/morluto/rea/issues/1169) +* **cli:** cancel routed JavaScript analysis in rea analyze ([#1156](https://github.com/morluto/rea/issues/1156)) ([089bbf5](https://github.com/morluto/rea/commit/089bbf58f3561e3f465c544bbcf8c307287b1256)) +* **cli:** complete cleanup after relayed interrupts ([#1202](https://github.com/morluto/rea/issues/1202)) ([911152a](https://github.com/morluto/rea/commit/911152a04d3aeb0d361141a8d54959009b269e49)) +* **cli:** list the read failure cause for an unreadable JSON input file ([db0afce](https://github.com/morluto/rea/commit/db0afce5f344268271c59acee04e96f986c5619a)) +* **cli:** list the read failure cause for an unreadable JSON input file ([6020df5](https://github.com/morluto/rea/commit/6020df53d9cd44845cf3b6b416db2d7802925578)) +* **cli:** resolve xrefs symbol selectors after address validation ([#1209](https://github.com/morluto/rea/issues/1209)) ([7e9c911](https://github.com/morluto/rea/commit/7e9c91199ecd133d26a51cb33b6e63e1f942df7e)) +* **config:** name the rejected setting and its constraint in configuration errors ([c3acc34](https://github.com/morluto/rea/commit/c3acc34475ca22387ea674839acfa1891b0b9f66)) +* **config:** name the rejected setting and its constraint in configuration errors ([0a0244d](https://github.com/morluto/rea/commit/0a0244db4212bc1f59dec4b925fa90b3b473136a)), closes [#1184](https://github.com/morluto/rea/issues/1184) +* **doctor:** find the Homebrew Hopper cask without writing Homebrew caches ([98b07d0](https://github.com/morluto/rea/commit/98b07d07ddd20bea2c3bdf8d55ac2776a263bcf4)) +* **doctor:** find the Homebrew Hopper cask without writing Homebrew caches ([a503376](https://github.com/morluto/rea/commit/a503376b2f9d9ba14d1602e58e0e93059e9d9181)), closes [#1165](https://github.com/morluto/rea/issues/1165) +* **domain:** report target read-permission denials as access_denied ([f36c10f](https://github.com/morluto/rea/commit/f36c10f9e8dc45a298d668e608f8e945bde487cf)) +* **domain:** report target read-permission denials as access_denied ([d0ff57a](https://github.com/morluto/rea/commit/d0ff57a45c8da8938e7ae16d00bfd5ec63310af3)), closes [#1188](https://github.com/morluto/rea/issues/1188) +* **electron:** resolve effective preload after option overrides ([#1286](https://github.com/morluto/rea/issues/1286)) ([411498d](https://github.com/morluto/rea/commit/411498d45f860eba2fbc9d7051af20237b7a4cb1)) +* emit v-mode-compatible patterns for tool schemas ([#1220](https://github.com/morluto/rea/issues/1220)) ([f0da05f](https://github.com/morluto/rea/commit/f0da05f67fff1411cf2f7a48a752ee7b348c71ff)) +* **errors:** report caller-selected evidence path failures as invalid input ([d4a598e](https://github.com/morluto/rea/commit/d4a598e93649607dd293a9c81bbf79c211bc8dd4)) +* **errors:** report caller-selected evidence path failures as invalid input ([db177c9](https://github.com/morluto/rea/commit/db177c91b83adb0c3edc4f9f6f06e31ac7523d53)) +* **evidence:** cancel exports before atomic publication ([16624f1](https://github.com/morluto/rea/commit/16624f1324e156d14025b2c346596c9781c07488)) +* **ghidra:** classify modern Swift manglings in swift type analysis ([#1208](https://github.com/morluto/rea/issues/1208)) ([6935dc7](https://github.com/morluto/rea/commit/6935dc7fe1258b340bb9cdfb8cecae66ef7bc0d4)) +* **ghidra:** do not run Java from a relative JAVA_HOME in doctor and setup ([04a516b](https://github.com/morluto/rea/commit/04a516b1e369f7e57e08d0653cc08292ac497e07)) +* **ghidra:** do not run Java from a relative JAVA_HOME in doctor and setup ([c3f1698](https://github.com/morluto/rea/commit/c3f169823f690371ecfdd2d1b3b07a5749438cf1)) +* **ghidra:** keep and name a runtime directory that close could not remove ([5b769d3](https://github.com/morluto/rea/commit/5b769d3a781c645ed8885e4fabf01a00f0bbc89b)) +* **ghidra:** keep and name a runtime directory that close could not remove ([b79d379](https://github.com/morluto/rea/commit/b79d379c25bcc8ed61571c41a94b912b5704a067)), closes [#1190](https://github.com/morluto/rea/issues/1190) +* **ghidra:** keep the NativeAOT target refusal's own recovery advice ([f198993](https://github.com/morluto/rea/commit/f198993f418e6aaa9755e7e6413abcb27c6cd684)) +* **ghidra:** preserve decoded return flow evidence ([b189c3c](https://github.com/morluto/rea/commit/b189c3ceb175dd9fa089eada9e9ca54e76307cb3)) +* **ghidra:** preserve decoded return flow evidence ([bcc8a77](https://github.com/morluto/rea/commit/bcc8a773e2a714e4899755b786a4fef1539bbace)) +* **ghidra:** reject relative installation and Java paths in doctor and setup ([8998438](https://github.com/morluto/rea/commit/8998438c23aa19e68f4ffa7574c5d341aa419165)) +* **ghidra:** reject relative installation and Java paths in doctor and setup ([5356856](https://github.com/morluto/rea/commit/53568568bf32b36274ba3a532f1e2cfb2daed271)), closes [#1183](https://github.com/morluto/rea/issues/1183) +* **ghidra:** report NativeAOT host and target refusals as unsupported, not failures ([cfb49eb](https://github.com/morluto/rea/commit/cfb49eb8a88fc51f460907024c51e05a2f272502)) +* **ghidra:** report NativeAOT host and target refusals as unsupported, not failures ([42c276a](https://github.com/morluto/rea/commit/42c276af1ec02473a7b6700a31292aae9e53d53e)), closes [#1185](https://github.com/morluto/rea/issues/1185) +* **ghidra:** resolve secondary symbols at function entries ([#1195](https://github.com/morluto/rea/issues/1195)) ([6fbdbd6](https://github.com/morluto/rea/commit/6fbdbd682038d012b04f0fe92c470cf1789fb101)) +* **ghidra:** stop dereferencing the removed error payload in address verification ([b80bd2d](https://github.com/morluto/rea/commit/b80bd2db966731fd3cfddfff7e92704053dbe955)) +* **ghidra:** stop dereferencing the removed error payload in address verification ([59fbaa2](https://github.com/morluto/rea/commit/59fbaa2d33359216534407f99f49705ac04a3426)) +* **ghidra:** use dot-free private session paths ([c3fc6c3](https://github.com/morluto/rea/commit/c3fc6c3aedc202e8ade015c4039a63e9f91cac6d)) +* **hopper:** keep the OS error when the FAT64 source cannot be reopened ([9f5dc52](https://github.com/morluto/rea/commit/9f5dc52be8420fb5e874595d63312bf80d07a3a2)) +* **hopper:** reserve Linux demo application before launch ([#1158](https://github.com/morluto/rea/issues/1158)) ([33d5ae0](https://github.com/morluto/rea/commit/33d5ae0b52b8684634ecf14d4e9469968c69d462)) +* **javascript:** allow cancellation during semantic graph commitment ([#1218](https://github.com/morluto/rea/issues/1218)) ([9405bd6](https://github.com/morluto/rea/commit/9405bd660def9946afaa5fcc1d99921a816911bf)) +* **javascript:** classify application input selection failures by cause ([fe5291e](https://github.com/morluto/rea/commit/fe5291e9166977a6ebbfa6ffcf7850af57192b34)) +* **javascript:** classify application input selection failures by cause ([0a14bbb](https://github.com/morluto/rea/commit/0a14bbbf05e0e61c98e06326fe7136e52fa4fb3c)) +* **javascript:** keep Wakaru version stderr out of the refusal message ([6489d58](https://github.com/morluto/rea/commit/6489d58851d055fd7ce621000d960bb42a0e4ce0)) +* **javascript:** match source-map originals that name parent directories ([#1215](https://github.com/morluto/rea/issues/1215)) ([889fb37](https://github.com/morluto/rea/commit/889fb374df0f8986f49e9d61b0fefd536327f781)) +* **javascript:** omit self-referential static references with disclosure ([#1157](https://github.com/morluto/rea/issues/1157)) ([b620e2a](https://github.com/morluto/rea/commit/b620e2a2bdcf3683b494d137bc409813735d5572)) +* **javascript:** preserve alias and container uncertainty ([73e98b2](https://github.com/morluto/rea/commit/73e98b2516dd792ea7b510aeed6b71f384bea21d)) +* **javascript:** preserve graphs with async chunk self-references ([#1152](https://github.com/morluto/rea/issues/1152)) ([7220166](https://github.com/morluto/rea/commit/72201668ed88c2cc822a07c08cf35a1e5ba88f35)) +* **javascript:** preserve property paths and uncertain slot presence ([475a0f8](https://github.com/morluto/rea/commit/475a0f84dac63d710e032bc7f731c1a3bda624ec)) +* **javascript:** reject encoded separators joined by HTML URL whitespace ([2ddd945](https://github.com/morluto/rea/commit/2ddd9456cd405f081784a4b3cb02cb77cd90fbd6)) +* **javascript:** reject encoded separators joined by HTML URL whitespace ([fb57c86](https://github.com/morluto/rea/commit/fb57c8643fb8b4733cbac9090ef58fd13a3b5347)) +* **javascript:** report located sources with differing digests as modified ([#1216](https://github.com/morluto/rea/issues/1216)) ([01174c4](https://github.com/morluto/rea/commit/01174c4a81fea109ae712ea1a746a83996f928ac)) +* **javascript:** resolve HTML script URLs after URL whitespace and percent decoding ([d601b80](https://github.com/morluto/rea/commit/d601b8016eaeb2955cea4e4c0aca10d17e7d12a7)) +* **javascript:** resolve HTML script URLs after URL whitespace and percent decoding ([502528c](https://github.com/morluto/rea/commit/502528c58df54c7b34eefdb5837f36e58f473405)), closes [#1236](https://github.com/morluto/rea/issues/1236) +* **javascript:** resolve package exports targets only to the exact file ([#1181](https://github.com/morluto/rea/issues/1181)) ([2a620c0](https://github.com/morluto/rea/commit/2a620c06cdcaa32844c4a80aeb3df1793f1ce09e)), closes [#1174](https://github.com/morluto/rea/issues/1174) +* keep the Ghidra session root free of dot-prefixed path elements ([a8b8288](https://github.com/morluto/rea/commit/a8b8288396cf2e053db768ef03f4db756aa8f71e)) +* **managed:** preserve literal library names during native matching ([81b70bc](https://github.com/morluto/rea/commit/81b70bc358031686c9d7afd049f21719c67a9525)) +* **managed:** separate metadata and signature completeness ([2f02eff](https://github.com/morluto/rea/commit/2f02eff9887fc715c33f5d8770a6e6191ba70ca9)) +* **mcp:** advertise input patterns without look-around ([1f099a6](https://github.com/morluto/rea/commit/1f099a6fc00b08fb0283dcabc5a238025d4c4c8b)) +* **mcp:** advertise input patterns without look-around ([a8701ea](https://github.com/morluto/rea/commit/a8701eaf489692449739d5b2490502b1a14951c5)), closes [#1282](https://github.com/morluto/rea/issues/1282) +* **mcp:** deliver tool errors within advertised schema contracts ([da606ff](https://github.com/morluto/rea/commit/da606ff77718d9a3b10426fcf68c098138e6dcfa)), closes [#1261](https://github.com/morluto/rea/issues/1261) +* **mcp:** deliver typed errors without invalid structured output ([#1277](https://github.com/morluto/rea/issues/1277)) ([7e96f25](https://github.com/morluto/rea/commit/7e96f25f8b1380a13a086a68f8d5a70380468151)) +* **mcp:** emit portable Unicode NUL patterns ([#1230](https://github.com/morluto/rea/issues/1230)) ([aa5750c](https://github.com/morluto/rea/commit/aa5750c263632d98d626c5ca3b985bb1519d2395)) +* **mcp:** measure tool errors against their text-only delivery ([fe34ec2](https://github.com/morluto/rea/commit/fe34ec2ef3e2968eeb06f64a1a0fdb8b825f56c4)) +* **mcp:** measure tool errors against their text-only delivery ([7b51121](https://github.com/morluto/rea/commit/7b51121f7cee21a5938f10ac3b5762e0bb41a58d)) +* **mcp:** only recommend exporting retained evidence ([5f749c2](https://github.com/morluto/rea/commit/5f749c2096af2617d4b6b387ff19c13001af8e54)) +* name host and tool requirements in optional adapter refusals ([68cb02f](https://github.com/morluto/rea/commit/68cb02fe8b123b9a0778c0065c13a15bcf0e577d)) +* name host and tool requirements in optional adapter refusals ([170d0bf](https://github.com/morluto/rea/commit/170d0bf9e2d45b2512ad556c02f31bdc81ea03ca)) +* **native:** distinguish batch selectors from resolved entries ([13c3b68](https://github.com/morluto/rea/commit/13c3b68730df80330fd867d921dea38770d5f880)) +* **native:** distinguish batch selectors from resolved entries ([bfaa5a6](https://github.com/morluto/rea/commit/bfaa5a6c2c0ddc9e6fcf16cd11ad06f24db174a2)) +* **native:** name the CLI flag that selects another plist ([9b69503](https://github.com/morluto/rea/commit/9b6950373cfaa1a2c0d28287bfadd4a421afb9e9)) +* **native:** name the plist selection that works when Info.plist is missing ([5612496](https://github.com/morluto/rea/commit/5612496f6d34a462dcd0fb69fa38337592e2f72d)) +* **native:** name the plist selection that works when Info.plist is missing ([a6fdf42](https://github.com/morluto/rea/commit/a6fdf426bd98c8cf7b7a7f589208d3193784062f)) +* **native:** refuse truncated executable headers at target admission ([d39a450](https://github.com/morluto/rea/commit/d39a450bdfac425962c3a6a6f47b45600057a230)) +* **native:** refuse truncated executable headers at target admission ([0b04d38](https://github.com/morluto/rea/commit/0b04d384cca4f22f271d60bcfe67f79cab89c8de)), closes [#1189](https://github.com/morluto/rea/issues/1189) +* **process:** apply one timeout rule to both execFileOutput modes ([3d32819](https://github.com/morluto/rea/commit/3d328193d69a63a355644c51bfb70f524d99bca9)) +* **process:** await cleanup on CLI and MCP cancellation ([f6fe575](https://github.com/morluto/rea/commit/f6fe575094658e99ced78d45f385633fbfaaae32)) +* **process:** keep ports before a chunk-final period ([184ed97](https://github.com/morluto/rea/commit/184ed970b9021552a5454ced20d202d10cabcbb8)) +* **process:** localize capture truncation diagnostics ([#1284](https://github.com/morluto/rea/issues/1284)) ([33bf585](https://github.com/morluto/rea/commit/33bf585185ffcaea63d658e2d3145c900a680485)) +* **process:** normalize ports that end a sentence ([098d769](https://github.com/morluto/rea/commit/098d76900effdbc682b0f97bcde7f8711380ecea)) +* **process:** normalize ports that end a sentence ([db98a51](https://github.com/morluto/rea/commit/db98a51dd1750b09b3905e18efac526f7ebf90f7)) +* **process:** preserve numeric output and original PTY evidence ([c5c75c3](https://github.com/morluto/rea/commit/c5c75c38c3a4ff0153513b8f8ad600d8a5bacc09)) +* **process:** preserve numeric output and original PTY evidence ([00d8e44](https://github.com/morluto/rea/commit/00d8e44cbf82caa51709c2e0857fbaa69ea329b7)) +* **process:** preserve unknown filesystem absence in partial captures ([c8544b1](https://github.com/morluto/rea/commit/c8544b1574a32838da6d4ed40f2b72582edb60dd)) +* **process:** refuse malformed timeouts for stoppable commands ([136d4aa](https://github.com/morluto/rea/commit/136d4aab18d822f0f908096b8acfac556ef1873b)) +* **process:** refuse malformed timeouts for stoppable commands ([59c91c8](https://github.com/morluto/rea/commit/59c91c88fe88210b4b22b9f1365a16567513da4a)) +* **process:** require current captures and preserve cleanup failures ([2a77469](https://github.com/morluto/rea/commit/2a7746998d47446c4db6d4f524e0f183d6803f3f)) +* **process:** retain known events from incomplete captures ([5eb0049](https://github.com/morluto/rea/commit/5eb0049a9f502b404f30e48c3fe3430a942bb0b5)) +* **process:** stop cancelled Swift helper builds before removing their files ([cf41561](https://github.com/morluto/rea/commit/cf415619cadcfcb18cda59a54b26c9d164f750a4)) +* **process:** stop cancelled Swift helper builds before removing their files ([c717204](https://github.com/morluto/rea/commit/c7172047951e7dbb9df58b57ff1b43ac9bd47909)), closes [#1173](https://github.com/morluto/rea/issues/1173) +* **process:** stop timed-out commands with the caller's stop signal ([4b38d18](https://github.com/morluto/rea/commit/4b38d1899566089d19b9fd137202f7d86b62fc6f)) +* **process:** stop timed-out commands with the caller's stop signal ([063de50](https://github.com/morluto/rea/commit/063de5014f19e85c38b6bec5984de4f38e71adaa)) +* **process:** treat non-ASCII letters as port continuations ([ad813e4](https://github.com/morluto/rea/commit/ad813e473b094ab0d3ab30798b7d252e2f4beb94)) +* **process:** validate terminal byte totals against retained frames ([69833fb](https://github.com/morluto/rea/commit/69833fb0d0fe9b320b5745a992822342f2c54a92)) +* **process:** validate terminal byte totals against retained frames ([39eb058](https://github.com/morluto/rea/commit/39eb0587c95ad028bb961c539ad1f326a1e8d81c)) +* **providers:** preserve observations and primary cleanup failures ([0696bde](https://github.com/morluto/rea/commit/0696bde2660bb5d6538d8c01da15aa023312aa9f)) +* **reference:** represent unreadable symlink targets explicitly ([b7b4333](https://github.com/morluto/rea/commit/b7b433370310c3ffe33d5027d8393151d5e862da)) +* restore caching, preserve failures, and verify fixture claims ([#1211](https://github.com/morluto/rea/issues/1211)) ([27a9cea](https://github.com/morluto/rea/commit/27a9ceade7232c1c9a24dc7d454ae060948183a1)) +* **server:** report 2025-era client identity and features in binary_session ([e6abaef](https://github.com/morluto/rea/commit/e6abaefbbc2bd81a6be34cbe71b87be801158c16)) +* **server:** report 2025-era client identity and features in binary_session ([b8312fa](https://github.com/morluto/rea/commit/b8312fa8d184ba9f422d1f5592fb41e49811544a)), closes [#1167](https://github.com/morluto/rea/issues/1167) +* **session:** require an open target for session-bound native and artifact tools ([d8e314c](https://github.com/morluto/rea/commit/d8e314cb24e7a4a494347e45474234e0aad74ad1)) +* **session:** require an open target for session-bound native and artifact tools ([cf77d07](https://github.com/morluto/rea/commit/cf77d073fc06ab95ce4181c30d68b1346e990b64)), closes [#1166](https://github.com/morluto/rea/issues/1166) +* **session:** retain failed provider cleanup for lifecycle retries ([#1260](https://github.com/morluto/rea/issues/1260)) ([24a3aa0](https://github.com/morluto/rea/commit/24a3aa08d1f69e25b441f086300ba3082d860a35)) +* **setup:** keep Codex TOML comments when adding or removing REA ([f5539cf](https://github.com/morluto/rea/commit/f5539cfc2f6c0daf6c275fc97f3351e2cf89b2c3)) +* **setup:** keep Codex TOML comments when adding or removing REA ([e9c48a6](https://github.com/morluto/rea/commit/e9c48a61e4c2c05c5b77ef4a815c5b2a65a9337e)), closes [#1163](https://github.com/morluto/rea/issues/1163) +* **setup:** preserve initial backups and Codex comments ([#1204](https://github.com/morluto/rea/issues/1204)) ([6051cb2](https://github.com/morluto/rea/commit/6051cb2c0c723d88dc43ee5ef8a96971bf84d49e)) +* **setup:** stop remaining uninstall removals after a client fails ([fd975c7](https://github.com/morluto/rea/commit/fd975c75fa353840e6e887232ca68496cf8705ea)) +* **setup:** stop uninstall before removals when a client config is unsafe ([4fb2f3e](https://github.com/morluto/rea/commit/4fb2f3e6ed0233505eada3cddeeff0ea0bfc6fe5)) +* **setup:** stop uninstall before removals when a client config is unsafe ([5cc841d](https://github.com/morluto/rea/commit/5cc841d5c154f692bdc257e106cc4b212dc19dc0)), closes [#1164](https://github.com/morluto/rea/issues/1164) +* **snapshot:** report query workflow and Evidence counts separately ([04aef6d](https://github.com/morluto/rea/commit/04aef6df331634238cfc61f320ba4a4e720750a4)) +* **snapshot:** report query workflow and Evidence counts separately ([0e77953](https://github.com/morluto/rea/commit/0e779533a9108a550b4d10dcb3920f91c7d48989)) +* **website:** clarify Android host and JDK requirements ([5691606](https://github.com/morluto/rea/commit/5691606aa948bddc641e3ecbccf5375a12b65924)) +* **website:** identify publication verifier requests ([e6905c1](https://github.com/morluto/rea/commit/e6905c18e09c41e04525fb1a84575483df789204)) +* **windows:** retain runtime authority after cleanup failure ([af7a439](https://github.com/morluto/rea/commit/af7a43963351c655eb86197bf52ae798a04e9c22)) +* **windows:** retain unsettled jobs for cleanup retry ([76b214e](https://github.com/morluto/rea/commit/76b214e45fa05fe723e216894327185b9b4e6f53)) + + +### Performance Improvements + +* **mcp:** share repeated output schema definitions. ([441813c](https://github.com/morluto/rea/commit/441813c0708dbee82ef554c91e973ae02964bf2e)) + +* **hopper:** resolve string search records once per query ([#1229](https://github.com/morluto/rea/issues/1229)) ([9426c3f](https://github.com/morluto/rea/commit/9426c3f1bbb94711d8b33097e604b9b8ed853b5e)) +* **mcp:** reuse input schemas without losing caller guidance ([#1162](https://github.com/morluto/rea/issues/1162)) ([e1afbc1](https://github.com/morluto/rea/commit/e1afbc1914cc7ff90265313e942f34ea4a58a4fc)) +* **snapshot:** avoid redundant result copies and serialization ([552634d](https://github.com/morluto/rea/commit/552634d634655a722b2204cfbc4b29f6d442c294)) +* **snapshot:** avoid redundant result copies and serialization ([569d2bc](https://github.com/morluto/rea/commit/569d2bc6b9f600114267a4c69f8400393ea1bc2f)) + + +### Code Refactoring + +* **domain:** remove obsolete comparison representations ([5510b27](https://github.com/morluto/rea/commit/5510b27d7f863a3df26212fba4a59f8df0da3712)) +* enforce canonical evidence and provider boundaries ([63bf914](https://github.com/morluto/rea/commit/63bf91405cf97b114a84f337fb1272d98a267999)) +* remove forwarding exports and redundant aliases ([ad59531](https://github.com/morluto/rea/commit/ad59531a960a0c51ef6857fa1391270dda0fa7a4)) +* **schemas:** share portable identifier and base64 patterns ([#1227](https://github.com/morluto/rea/issues/1227)) ([954badb](https://github.com/morluto/rea/commit/954badbaaadd24a210190ce3015e40c23d327567)) + + +### Documentation + +* add French README translation ([84094af](https://github.com/morluto/rea/commit/84094af54a4e0a6247445e59abff27bc4eca361b)) +* add French README translation ([9664b2b](https://github.com/morluto/rea/commit/9664b2b101fe4ac334b2911f9210b50d58d90a89)) +* celebrate 30,000 GitHub stars 🎉 ([6987cb0](https://github.com/morluto/rea/commit/6987cb066a5aa5e51480bb06a93a758e6f67cd1e)) +* celebrate 30,000 GitHub stars 🎉 ([beca997](https://github.com/morluto/rea/commit/beca9977eb2b18fc7b9844cff0ca70004b6ff21a)) +* clarify REA has no affiliated cryptocurrency or token ([#1214](https://github.com/morluto/rea/issues/1214)) ([c2d8146](https://github.com/morluto/rea/commit/c2d8146f94c7533eb87681c2405e93bdfef21b59)) +* explain 6.2 contract and saved-data migration ([#1304](https://github.com/morluto/rea/issues/1304)) ([c267e99](https://github.com/morluto/rea/commit/c267e9922751c03df312655ebd623de1b480215c)) +* **ghidra:** explain supported heap and CPU controls ([#1278](https://github.com/morluto/rea/issues/1278)) ([0c6852b](https://github.com/morluto/rea/commit/0c6852b392b34319a6fd2c6dffcac10cee51ab94)), closes [#1255](https://github.com/morluto/rea/issues/1255) +* keep the 30k milestone in Star History ([#1217](https://github.com/morluto/rea/issues/1217)) ([c399670](https://github.com/morluto/rea/commit/c399670653884673158f314ed38260aef74da593)) +* require focused brittleness cleanup and executable examples ([d6832c3](https://github.com/morluto/rea/commit/d6832c3632847cf3e62d4082b4b8b8d9af554633)) +* thank feature request contributors ([9db1fd0](https://github.com/morluto/rea/commit/9db1fd0bd7b17ed1dd21b9c72dabfa4ec6c23a3f)) +* **website:** continue the Calculator example with reconstruction ([4578647](https://github.com/morluto/rea/commit/4578647c59a7487bce597a65be6eab8be0412e84)) +* **website:** continue the Calculator example with reconstruction ([18a1e8c](https://github.com/morluto/rea/commit/18a1e8cd0efe14c06fd14aabe0c318d2ae390f78)) +* **website:** explain SEO maintenance and indexing follow-up ([bb8ff2c](https://github.com/morluto/rea/commit/bb8ff2cfba638ee3a77f951c01e98340c757f525)) +* **website:** introduce the worked homepage examples ([f6f5c16](https://github.com/morluto/rea/commit/f6f5c160979624cdcb33928f1a77cf000de403d4)) +* **website:** invite deeper projects and reader feedback ([3fb9ffa](https://github.com/morluto/rea/commit/3fb9ffaa4d67685412873cbd3101c64fabbeaff3)) + + +### Tests + +* **apple:** verify compiled Mach-O root occurrence facts ([#1300](https://github.com/morluto/rea/issues/1300)) ([4bb4c6f](https://github.com/morluto/rea/commit/4bb4c6fe6d34525c7665a9d38b584b026dd5cdd9)) +* **artifacts:** assert asset-catalog target refusal only on macOS ([44d5b4b](https://github.com/morluto/rea/commit/44d5b4b25e0831769c1bd4e5426ef498d0bd3c74)) +* **artifacts:** pin per-occurrence roles for direct Mach-O roots and shared bytes ([701d90a](https://github.com/morluto/rea/commit/701d90aba48aaf4f23e1a73e46ebf9968fb85293)) +* **artifacts:** pin per-occurrence roles for direct Mach-O roots and shared bytes ([b9e29c5](https://github.com/morluto/rea/commit/b9e29c52d483704c64cd88f87eaa117066288602)), closes [#1234](https://github.com/morluto/rea/issues/1234) [#1235](https://github.com/morluto/rea/issues/1235) +* **artifacts:** read /bin/ls slice layout from its FAT table ([#1223](https://github.com/morluto/rea/issues/1223)) ([c89b3a0](https://github.com/morluto/rea/commit/c89b3a00dce8df36ddb696b59c80e1adc6aceac1)) +* **artifacts:** verify compiled Mach-O roles and permissions ([4bb4c6f](https://github.com/morluto/rea/commit/4bb4c6fe6d34525c7665a9d38b584b026dd5cdd9)) +* consolidate redundant assertions into boundary workflows ([b71a591](https://github.com/morluto/rea/commit/b71a591a60e3fa5333889e3cf97e05f4ae03c686)) +* **ghidra:** preserve selected verification resource limits ([1c3766a](https://github.com/morluto/rea/commit/1c3766a8bcc8a2b6af679cdaa92a73fec42b3372)) +* **ghidra:** size oversized annotations for canonical delivery ([1e34197](https://github.com/morluto/rea/commit/1e341973cfad1dbf06755f3a086ffc23d42a723c)) +* **ghidra:** use host-native absolute session root fixtures ([1e83d27](https://github.com/morluto/rea/commit/1e83d270c2098b1bcb59591698a257a05d2296fc)) +* **javascript:** expect the invalid input_path code in the streamed CLI failure test ([d186ca7](https://github.com/morluto/rea/commit/d186ca7e41928fc2748de2631f5cb43115776571)) +* **mcp:** read bundle failures from public error content ([69c3b32](https://github.com/morluto/rea/commit/69c3b32a21c90ea96194fb695f7b58992e8b3714)) +* **mcp:** read typed errors in canonical Evidence regressions ([fd46cff](https://github.com/morluto/rea/commit/fd46cff017f0110aaab1216764cf01a71b341766)) +* **mcp:** validate public error diagnostics in acceptance workflows ([09058eb](https://github.com/morluto/rea/commit/09058ebc4a68c76d865a92dbddb65811ba8344f7)) +* **native:** assert batch identity in production registration ([933fcb3](https://github.com/morluto/rea/commit/933fcb33c1fa1eae109228b89c1200abb7745eb8)) +* **native:** build the .app fixture executable with a complete Mach-O header ([facaae8](https://github.com/morluto/rea/commit/facaae865af243656ab8f557aeb42f5909748f2b)) +* **process:** check malformed capture choices concurrently ([6020a0b](https://github.com/morluto/rea/commit/6020a0b3683ce16e1441963473605f870c247e29)) +* **process:** check malformed capture choices concurrently ([48de11c](https://github.com/morluto/rea/commit/48de11ce2e5af9810fc97d1c2f89df56bf3a3d4d)) +* remove duplicate workflow examples and self assertions ([d6d1cd2](https://github.com/morluto/rea/commit/d6d1cd248506015b59a2abdbbb84e3dbd02388fc)) + + +### Continuous Integration + +* **website:** allow explicitly requested Pages-only publication ([796b65e](https://github.com/morluto/rea/commit/796b65e1cd15f3cf819396716320db007655ee3f)) +* **website:** allow explicitly requested Pages-only publication ([864160d](https://github.com/morluto/rea/commit/864160d8858fad3c0afebff81c31b090a1ebf823)) +* **website:** allow explicitly requested Pages-only publication ([#1205](https://github.com/morluto/rea/issues/1205)) ([796b65e](https://github.com/morluto/rea/commit/796b65e1cd15f3cf819396716320db007655ee3f)) +* **website:** publish Cloudflare and Pages from one artifact ([761881c](https://github.com/morluto/rea/commit/761881cec33b18d7228bae5e2093e5d44b96ceb1)) + ## [6.1.0](https://github.com/morluto/rea/compare/rea-agents-6.0.0...rea-agents-6.1.0) (2026-10-09) diff --git a/docs/installation.md b/docs/installation.md index a0be32920..80bf93f7e 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -659,7 +659,7 @@ For a client that requires manual configuration, use: "mcpServers": { "rea": { "command": "npx", - "args": ["-y", "rea-agents@6.1.0", "mcp"] + "args": ["-y", "rea-agents@6.2.0", "mcp"] } } } diff --git a/docs/migration-6.2.md b/docs/migration-6.2.md index 76cf04509..38baae073 100644 --- a/docs/migration-6.2.md +++ b/docs/migration-6.2.md @@ -40,6 +40,13 @@ Lifecycle and other non-Evidence tools still use their own advertised output contracts. Do not assume every successful tool returns Evidence. Consult [`tools/list` and the result guide](mcp-contracts.md#tool-results). +A transport `resource_constraint` error can include a retained +`details.reported_limits.evidence_reference`. Use `inspect_analysis_view` or +`export_evidence_bundle` on the same connection to consume the complete retained +Evidence. Response-budget settings are captured when the server starts; recreate +the server to change them, and keep the client's receive budget aligned. Raising +the server budget does not change the client's limit or analysis coverage. + Every Evidence record now requires `analysis_profile`, either its observed profile object or `null`. The field participates in Evidence identity. Records that omitted it cannot be migrated by inserting `null` while retaining the old diff --git a/package-lock.json b/package-lock.json index 84a8cee63..9e674e202 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rea-agents", - "version": "6.1.0", + "version": "6.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rea-agents", - "version": "6.1.0", + "version": "6.2.0", "license": "MIT", "dependencies": { "@babel/parser": "8.0.4", diff --git a/package.json b/package.json index 48b36ecbd..0ec211497 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "rea-agents", "mcpName": "io.github.morluto/rea", - "version": "6.1.0", + "version": "6.2.0", "description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.", "license": "MIT", "repository": { @@ -232,7 +232,7 @@ "oxfmt", "oxlint --fix" ], - "*.{json,md,yml,yaml}": "oxfmt" + "*.{json,md,yml,yaml}": "oxfmt --no-error-on-unmatched-pattern" }, "dependencies": { "@babel/parser": "8.0.4", diff --git a/server.json b/server.json index 71634f80c..74c21bec1 100644 --- a/server.json +++ b/server.json @@ -8,13 +8,13 @@ "url": "https://github.com/morluto/rea", "source": "github" }, - "version": "6.1.0", + "version": "6.2.0", "packages": [ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "rea-agents", - "version": "6.1.0", + "version": "6.2.0", "runtimeHint": "npx", "transport": { "type": "stdio" diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index cad237647..77fc01683 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -1,7 +1,7 @@ /** Generated from package.json and package-lock.json; do not edit. */ export const PACKAGE_METADATA = { name: "rea-agents", - version: "6.1.0", // x-release-please-version + version: "6.2.0", // x-release-please-version serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", From b112d44a3961939881779c81a57e7a3f9d1372f7 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:12:58 +0800 Subject: [PATCH 007/189] fix(native)!: preserve unknown Objective-C metadata BREAKING CHANGE: Objective-C attribute tokens now contain only name and value. Properties report nullable atomicity and readonly facts; class flags, ivar counts, and method requirement flags are nullable when unobserved. --- docs/native-investigation.md | 14 ++- scripts/verify/apple/dispatch.mjs | 50 ++++++++++ .../references/native-and-artifacts.md | 9 ++ src/domain/native/objcSwiftMetadata.test.ts | 9 ++ src/domain/native/objcSwiftMetadata.ts | 29 +++--- src/native/AppleDispatchMetadata.test.ts | 99 ++++++++++++++++++- src/native/AppleMachoFixups.test.ts | 27 +++-- src/native/AppleObjcDispatchFacets.ts | 6 +- src/native/AppleObjcProperties.ts | 26 +++-- tests/conformance/native/dispatch.m | 1 + 10 files changed, 225 insertions(+), 45 deletions(-) diff --git a/docs/native-investigation.md b/docs/native-investigation.md index 2d71ad69a..4dad23b3b 100644 --- a/docs/native-investigation.md +++ b/docs/native-investigation.md @@ -96,8 +96,18 @@ complete observation. So an external superclass resolves from its `_OBJC_CLASS_$_` bind (for example `NSObject`). The `pointer_fixups` coverage facet names the mechanism. - Class properties, with parsed attributes, and `__objc_catlist` categories are - also decoded. Categories record the extended class, local or external, plus + Class properties preserve each encoded attribute as a raw `{name, value}` + pair, for example `{ name: "N", value: "" }`, and report atomicity on the + property: `N` means `nonatomic`; a complete typed attribute string without + `N` means the Objective-C default `atomic`; + missing or incomplete attribute metadata leaves `atomicity` and any + unestablished read-only value null. `is_meta_class`, `is_root_class`, and + `ivar_count` are also nullable when the selected provider exposes only symbol + names. Class implementation methods have null `is_required` and `is_optional` + fields because those facts apply to protocol declarations; decoded protocol + method lists retain their observed required/optional values. Class properties + and `__objc_catlist` categories are also decoded. Categories record the + extended class, local or external, plus their methods, protocols and properties; category methods appear as implementations with a `category`. Swift field-offset globals that are only initialized at runtime stay unresolved. Generic, resilient, async and diff --git a/scripts/verify/apple/dispatch.mjs b/scripts/verify/apple/dispatch.mjs index bf86d85d6..411e3e32e 100644 --- a/scripts/verify/apple/dispatch.mjs +++ b/scripts/verify/apple/dispatch.mjs @@ -1,3 +1,4 @@ +import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -6,6 +7,12 @@ import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { parseBinaryTarget } from "../../../dist/application/BinaryTargetResolver.js"; import { inspectAppleDispatchMetadata } from "../../../dist/native/AppleDispatchMetadata.js"; +import { + artifactCliEvidence, + artifactMcpResult, + withArtifactMcp, +} from "../../lib/artifact-e2e.mjs"; +import { nativeDispatchMetadataResultSchema } from "../../../dist/domain/native/objcSwiftMetadata.js"; if (process.platform !== "darwin") throw new Error( @@ -61,6 +68,30 @@ const checkObjc = (metadata, mode) => { const objcCoverage = metadata.coverage.find( ({ facet }) => facet === "objc_class_method_ivar_metadata", ); + assert.equal(fixture?.is_meta_class, false); + assert.equal(fixture?.is_root_class, false); + assert.equal( + fixture?.properties.find(({ name }) => name === "fixtureName")?.atomicity, + "nonatomic", + ); + assert.equal( + fixture?.properties.find(({ name }) => name === "atomicValue")?.atomicity, + "atomic", + ); + for (const method of fixture.methods) { + assert.equal(method.is_required, null); + assert.equal(method.is_optional, null); + } + for (const property of fixture.properties) + for (const attribute of property.attributes) + assert.deepEqual(Object.keys(attribute).sort(), ["name", "value"]); + const protocol = metadata.objc_protocols.find( + ({ name }) => name === "ReaDispatchProtocol", + ); + assert.equal(protocol?.methods[0]?.is_required, true); + assert.equal(protocol?.methods[0]?.is_optional, false); + assert.equal(protocol?.optional_methods[0]?.is_required, false); + assert.equal(protocol?.optional_methods[0]?.is_optional, true); if ( !metadata.objc_dispatch_implementations.some( (item) => @@ -162,6 +193,25 @@ try { await exec("/usr/bin/strip", ["-x", objcPath]); const { target, metadata } = await inspect(objcPath); checkObjc(metadata, mode); + if (mode.mode === "chained" && variant === "stripped") { + const cli = await artifactCliEvidence( + "inspect-native-dispatch-metadata", + objcPath, + ); + const cliResult = nativeDispatchMetadataResultSchema.parse( + cli.normalized_result, + ); + assert.equal(cliResult.target_sha256, target.sha256); + checkObjc(cliResult.result, mode); + await withArtifactMcp(objcPath, async (client) => { + const mcpResult = nativeDispatchMetadataResultSchema.parse( + await artifactMcpResult(client, "inspect_native_dispatch_metadata"), + ); + assert.equal(mcpResult.target_sha256, target.sha256); + checkObjc(mcpResult.result, mode); + assert.deepEqual(mcpResult.result, cliResult.result); + }); + } results.push({ variant: `objc-${mode.mode}-${variant}`, target_sha256: target.sha256, diff --git a/skill-src/reverse-engineer-anything/references/native-and-artifacts.md b/skill-src/reverse-engineer-anything/references/native-and-artifacts.md index 08e2ac874..f47017171 100644 --- a/skill-src/reverse-engineer-anything/references/native-and-artifacts.md +++ b/skill-src/reverse-engineer-anything/references/native-and-artifacts.md @@ -60,6 +60,15 @@ use inclusive ends and can contain gaps. Do not treat the enclosing span as code For packed targets, retain the original and separately derived artifact identities; decompiling an unpacking stub does not recover the unpacked program. +When reading Objective-C dispatch metadata, distinguish class implementation +methods from protocol requirements: class methods report null requirement +flags, while decoded protocol declarations retain required and optional facts. +Property attributes remain raw name/value tokens; use the property's +`atomicity` field for the decoded `N` marker or the default atomic behavior. +Null class/meta flags, ivar counts, atomicity, or read-only values mean the +selected provider did not establish that fact. Symbol names alone do not prove +that a class is a root class or has no ivars. + ## Managed PE/CLI Start with `inspect_managed_artifact`. REA's canonical managed inspection is diff --git a/src/domain/native/objcSwiftMetadata.test.ts b/src/domain/native/objcSwiftMetadata.test.ts index e2fa3b765..c8a349248 100644 --- a/src/domain/native/objcSwiftMetadata.test.ts +++ b/src/domain/native/objcSwiftMetadata.test.ts @@ -14,6 +14,15 @@ describe("ObjC/Swift metadata", () => { ); expect(result.objc_classes).toHaveLength(1); expect(result.objc_dispatch_implementations).toHaveLength(1); + expect(result.objc_classes[0]).toMatchObject({ + is_meta_class: null, + is_root_class: null, + ivar_count: null, + }); + expect(result.objc_classes[0]?.methods[0]).toMatchObject({ + is_required: null, + is_optional: null, + }); expect(result.swift_symbols).toHaveLength(0); expect(result.coverage).toContainEqual( expect.objectContaining({ diff --git a/src/domain/native/objcSwiftMetadata.ts b/src/domain/native/objcSwiftMetadata.ts index 5a0f0e052..807c5dffd 100644 --- a/src/domain/native/objcSwiftMetadata.ts +++ b/src/domain/native/objcSwiftMetadata.ts @@ -12,10 +12,6 @@ export const objcMethodTypeSchema = z.enum([ export const objcPropertyAttributeSchema = z.strictObject({ name: z.string().min(1), value: z.string(), - is_weak: z.boolean().default(false), - is_atomic: z.boolean().default(false), - is_copy: z.boolean().default(false), - is_strong: z.boolean().default(false), }); /** Objective-C method metadata. */ @@ -23,8 +19,8 @@ export const objcMethodSchema = z.strictObject({ selector: z.string().min(1), method_type: objcMethodTypeSchema, address: z.number().int().nullable(), - is_required: z.boolean().default(false), - is_optional: z.boolean().default(false), + is_required: z.boolean().nullable(), + is_optional: z.boolean().nullable(), }); type ObjcMethod = z.infer; @@ -32,8 +28,9 @@ type ObjcMethod = z.infer; export const objcPropertySchema = z.strictObject({ name: z.string().min(1), type_encoding: z.string().nullable(), - attributes: z.array(objcPropertyAttributeSchema).default([]), - is_readonly: z.boolean().default(false), + attributes: z.array(objcPropertyAttributeSchema), + atomicity: z.enum(["atomic", "nonatomic"]).nullable(), + is_readonly: z.boolean().nullable(), getter: z.string().nullable(), setter: z.string().nullable(), }); @@ -50,12 +47,12 @@ export const objcProtocolSchema = z.strictObject({ export const objcClassSchema = z.strictObject({ name: z.string().min(1), super_class: z.string().nullable(), - is_meta_class: z.boolean().default(false), - is_root_class: z.boolean().default(false), + is_meta_class: z.boolean().nullable(), + is_root_class: z.boolean().nullable(), methods: z.array(objcMethodSchema).default([]), properties: z.array(objcPropertySchema).default([]), protocols: z.array(z.string()).default([]), - ivar_count: z.number().int().nonnegative().default(0), + ivar_count: z.number().int().nonnegative().nullable(), instance_size: z.number().int().nonnegative().nullable(), location: z .object({ @@ -380,20 +377,20 @@ export const inspectNativeDispatchMetadata = ( selector: implementation.selector, method_type: implementation.method_type, address: parseMetadataAddress(implementation.implementation_address), - is_required: false, - is_optional: false, + is_required: null, + is_optional: null, }); methodsByClass.set(implementation.class_name, methods); } const classes: ObjcClass[] = [...classNames].sort().map((name) => ({ name, super_class: null, - is_meta_class: false, - is_root_class: false, + is_meta_class: null, + is_root_class: null, methods: methodsByClass.get(name) ?? [], properties: [], protocols: [], - ivar_count: 0, + ivar_count: null, instance_size: null, })); const decodedImplementations = [...implementations.values()].sort( diff --git a/src/native/AppleDispatchMetadata.test.ts b/src/native/AppleDispatchMetadata.test.ts index a69f20183..b0758748e 100644 --- a/src/native/AppleDispatchMetadata.test.ts +++ b/src/native/AppleDispatchMetadata.test.ts @@ -3,7 +3,7 @@ import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js"; const base = 0x100000000n; const fixture = (relative = false) => { - const bytes = Buffer.alloc(2048); + const bytes = Buffer.alloc(4096); const u32 = (offset: number, value: number) => bytes.writeUInt32LE(value, offset); const ptr = (offset: number, target: number) => @@ -16,8 +16,8 @@ const fixture = (relative = false) => { u32(36, 152); bytes.write("__DATA", 40); ptr(56, 0); - bytes.writeBigUInt64LE(2048n, 64); - bytes.writeBigUInt64LE(2048n, 80); + bytes.writeBigUInt64LE(4096n, 64); + bytes.writeBigUInt64LE(4096n, 80); u32(92, 5); u32(96, 1); bytes.write("__objc_classlist", 104); @@ -33,6 +33,8 @@ const fixture = (relative = false) => { ptr(0x318, 0x450); ptr(0x320, 0x480); ptr(0x330, 0x500); + ptr(0x328, 0x700); + ptr(0x340, 0x600); u32(0x380, 1); ptr(0x398, 0x450); bytes.write("Fixture\0", 0x450); @@ -56,6 +58,34 @@ const fixture = (relative = false) => { u32(0x580, 8); bytes.write("state\0", 0x5a0); bytes.write("i\0", 0x5c0); + u32(0x600, 16); + u32(0x604, 3); + ptr(0x608, 0x640); + ptr(0x610, 0x650); + ptr(0x618, 0x660); + ptr(0x620, 0x670); + ptr(0x628, 0x680); + ptr(0x630, 0x690); + bytes.write("atomicValue\0", 0x640); + bytes.write("Tq\0", 0x650); + bytes.write("nonatomicValue\0", 0x660); + bytes.write("Tq,N\0", 0x670); + bytes.write("unknownValue\0", 0x680); + bytes.writeBigUInt64LE(1n, 0x700); + ptr(0x708, 0x740); + ptr(0x748, 0x900); + ptr(0x758, 0x800); + ptr(0x768, 0x840); + u32(0x780, 72); + u32(0x800, 24); + u32(0x804, 1); + ptr(0x808, 0x920); + u32(0x840, 24); + u32(0x844, 1); + ptr(0x848, 0x940); + bytes.write("FixtureProtocol\0", 0x900); + bytes.write("requiredAction:\0", 0x920); + bytes.write("optionalAction:\0", 0x940); return bytes; }; const provenance = { path: "/fixture/app", sha256: "a".repeat(64) }; @@ -92,6 +122,69 @@ describe("Apple dispatch binary metadata", () => { location: { file_offset: 0x508 }, }, ]); + expect(result.objc_classes[0]?.properties).toEqual([ + { + name: "atomicValue", + type_encoding: "q", + attributes: [{ name: "T", value: "q" }], + atomicity: "atomic", + is_readonly: false, + getter: null, + setter: null, + }, + { + name: "nonatomicValue", + type_encoding: "q", + attributes: [ + { name: "T", value: "q" }, + { name: "N", value: "" }, + ], + atomicity: "nonatomic", + is_readonly: false, + getter: null, + setter: null, + }, + { + name: "unknownValue", + type_encoding: null, + attributes: [], + atomicity: null, + is_readonly: null, + getter: null, + setter: null, + }, + ]); + expect(result.objc_classes[0]).toMatchObject({ + is_meta_class: false, + is_root_class: false, + ivar_count: 1, + }); + expect(result.objc_classes[1]).toMatchObject({ + is_meta_class: true, + is_root_class: false, + ivar_count: null, + }); + expect(result.objc_classes[0]?.methods[0]).toMatchObject({ + is_required: null, + is_optional: null, + }); + expect(result.objc_protocols[0]).toMatchObject({ + name: "FixtureProtocol", + methods: [ + { + selector: "requiredAction:", + is_required: true, + is_optional: false, + }, + ], + optional_methods: [ + { + selector: "optionalAction:", + is_required: false, + is_optional: true, + }, + ], + }); }, ); it("keeps unsupported pointers and record truncation explicit", () => { diff --git a/src/native/AppleMachoFixups.test.ts b/src/native/AppleMachoFixups.test.ts index f9218fc7b..d6c56e7b9 100644 --- a/src/native/AppleMachoFixups.test.ts +++ b/src/native/AppleMachoFixups.test.ts @@ -275,28 +275,27 @@ describe("Objective-C property attributes", () => { ).toEqual({ name: "title", type_encoding: '@"NSString"', + atomicity: "nonatomic", attributes: [ - expect.objectContaining({ - name: "T", - value: '@"NSString"', - }), - expect.objectContaining({ name: "C", is_copy: true }), - expect.objectContaining({ name: "N" }), - expect.objectContaining({ name: "G", value: "customTitle" }), - expect.objectContaining({ name: "V", value: "_title" }), + { name: "T", value: '@"NSString"' }, + { name: "C", value: "" }, + { name: "N", value: "" }, + { name: "G", value: "customTitle" }, + { name: "V", value: "_title" }, ], is_readonly: false, getter: "customTitle", setter: null, }); - expect(parsePropertyAttributes("count", "Tq,R,N")).toMatchObject({ + expect(parsePropertyAttributes("count", "Tq,R")).toMatchObject({ type_encoding: "q", is_readonly: true, + atomicity: "atomic", }); - expect( - parsePropertyAttributes("delegate", "T@,W,N,V_delegate").attributes[1], - ).toMatchObject({ - is_weak: true, - }); + expect(parsePropertyAttributes("count", "Tq,R,N").atomicity).toBe( + "nonatomic", + ); + expect(parsePropertyAttributes("count", "").atomicity).toBeNull(); + expect(parsePropertyAttributes("count", "R").atomicity).toBeNull(); }); }); diff --git a/src/native/AppleObjcDispatchFacets.ts b/src/native/AppleObjcDispatchFacets.ts index e23d4905d..14f0b42b8 100644 --- a/src/native/AppleObjcDispatchFacets.ts +++ b/src/native/AppleObjcDispatchFacets.ts @@ -216,7 +216,7 @@ export const decodeObjcDispatchFacets = (input: { `Superclass of ${name} requires external binding resolution`, ); const ivarList = read.pointer(ro + 48n); - let ivarCount = 0; + let ivarCount: number | null = meta ? null : 0; if (ivarList !== 0n && !meta) { const stride = read.u32(ivarList), count = read.u32(ivarList + 4n); @@ -276,8 +276,8 @@ export const decodeObjcDispatchFacets = (input: { BigInt(Number.MAX_SAFE_INTEGER) ? Number(BigInt(item.implementation_address)) : null, - is_required: false, - is_optional: false, + is_required: null, + is_optional: null, })), properties: readObjcPropertiesOf(read, read.pointer(ro + 64n), { owner: name, diff --git a/src/native/AppleObjcProperties.ts b/src/native/AppleObjcProperties.ts index 07dacbc1f..cd9c0774d 100644 --- a/src/native/AppleObjcProperties.ts +++ b/src/native/AppleObjcProperties.ts @@ -21,20 +21,32 @@ export const parsePropertyAttributes = ( attributes: string, ): ObjcProperty => { const tokens = attributes.length === 0 ? [] : splitAttributes(attributes); + const typeAttributes = tokens.filter((token) => token[0] === "T"); + const typeAttribute = + typeAttributes.length === 1 ? typeAttributes[0] : undefined; + const typeEncoding = + typeAttribute !== undefined && typeAttribute.length > 1 + ? typeAttribute.slice(1) + : null; const value = (code: string): string | null => - tokens.find((token) => token.startsWith(code))?.slice(1) ?? null; + tokens.find((token) => token[0] === code)?.slice(1) ?? null; return { name, - type_encoding: value("T"), + type_encoding: typeEncoding, attributes: tokens.map((token) => ({ name: token.slice(0, 1), value: token.slice(1), - is_weak: token === "W", - is_atomic: false, - is_copy: token === "C", - is_strong: token === "&", })), - is_readonly: tokens.includes("R"), + atomicity: tokens.includes("N") + ? "nonatomic" + : typeEncoding === null + ? null + : "atomic", + is_readonly: tokens.includes("R") + ? true + : typeEncoding === null + ? null + : false, getter: value("G"), setter: value("S"), }; diff --git a/tests/conformance/native/dispatch.m b/tests/conformance/native/dispatch.m index 3ccb5fb7c..2b83c1a4d 100644 --- a/tests/conformance/native/dispatch.m +++ b/tests/conformance/native/dispatch.m @@ -10,6 +10,7 @@ int state; } @property(nonatomic, copy) NSString *fixtureName; +@property NSInteger atomicValue; - (void)performAction:(id)sender; + (int)fixtureVersion; @end From cc7b5af0777fc68ebba10ec061244729ebf2357d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:13:24 +0800 Subject: [PATCH 008/189] fix(managed): bind graph facts to their source Evidence --- src/domain/managed/managedApplicationGraph.ts | 23 +- .../managedApplicationGraphNodeCoverage.ts | 11 - .../managed/managedApplicationGraphNodes.ts | 215 +++++++++++------- .../managedApplicationGraph.test.ts | 184 ++++++++++++--- 4 files changed, 309 insertions(+), 124 deletions(-) delete mode 100644 src/domain/managed/managedApplicationGraphNodeCoverage.ts diff --git a/src/domain/managed/managedApplicationGraph.ts b/src/domain/managed/managedApplicationGraph.ts index 57e845bf0..f99ebb47c 100644 --- a/src/domain/managed/managedApplicationGraph.ts +++ b/src/domain/managed/managedApplicationGraph.ts @@ -151,8 +151,8 @@ export const projectManagedApplicationGraph = ( }; const artifactNode = addArtifactNode(state); addArtifactIdentityNodes(state, artifactNode, parsed); - const memberCounts = addMemberNodes(state, artifactNode, parsed); - const boundaryCounts = addBoundaryNodes(state, artifactNode, parsed); + addMemberNodes(state, artifactNode, parsed); + addBoundaryNodes(state, artifactNode, parsed); const omissions = omittedCounts(parsed); const limitations = projectionLimitations(parsed, omissions); const graph = createJavaScriptApplicationGraph({ @@ -175,10 +175,16 @@ export const projectManagedApplicationGraph = ( summary: { graph_nodes: graph.nodes.length, graph_edges: graph.edges.length, - assemblies: parsed.artifact?.result.assembly === null ? 0 : 1, - modules: parsed.artifact?.result.module === null ? 0 : 1, - ...memberCounts, - ...boundaryCounts, + assemblies: countNodes(graph.nodes, "managed-assembly"), + modules: countNodes(graph.nodes, "managed-module"), + types: countNodes(graph.nodes, "managed-type"), + methods: countNodes(graph.nodes, "managed-method"), + fields: countNodes(graph.nodes, "managed-field"), + pinvoke_imports: countNodes(graph.nodes, "managed-pinvoke-import"), + native_implementations: countNodes( + graph.nodes, + "managed-native-implementation", + ), }, graph, coverage: managedGraphResultCoverage(omissions), @@ -191,6 +197,11 @@ export const projectManagedApplicationGraph = ( }); }; +const countNodes = ( + nodes: readonly ApplicationNode[], + kind: ApplicationNode["kind"], +): number => nodes.filter((node) => node.kind === kind).length; + const parseManagedInputs = ( input: ProjectManagedApplicationGraphInput, ): ParsedManagedGraphInput => ({ diff --git a/src/domain/managed/managedApplicationGraphNodeCoverage.ts b/src/domain/managed/managedApplicationGraphNodeCoverage.ts deleted file mode 100644 index 437f1d7f3..000000000 --- a/src/domain/managed/managedApplicationGraphNodeCoverage.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { ParsedManagedGraphInput } from "./managedApplicationGraph.js"; - -/** Derive module coverage from the best available managed evidence source. */ -export const moduleCoverageState = ( - parsed: ParsedManagedGraphInput, -): "complete" | "partial" | "unavailable" => - parsed.artifact !== null && parsed.artifact.result.module !== null - ? parsed.artifact.result.coverage.state - : parsed.members !== null && parsed.members.result.module !== null - ? parsed.members.result.coverage.state - : (parsed.boundaries?.result.coverage.state ?? "complete"); diff --git a/src/domain/managed/managedApplicationGraphNodes.ts b/src/domain/managed/managedApplicationGraphNodes.ts index bd5a72dba..cd631d018 100644 --- a/src/domain/managed/managedApplicationGraphNodes.ts +++ b/src/domain/managed/managedApplicationGraphNodes.ts @@ -6,7 +6,9 @@ import { import type { ApplicationGraphEvidence } from "../javascript/javascriptApplicationEvidenceSchemas.js"; import type { ApplicationNode } from "../javascript/javascriptApplicationGraphSchemas.js"; import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js"; +import type { Evidence } from "../evidence.js"; import { + type ManagedArtifactInspection, type ManagedMemberInspection, type ManagedNativeBoundaryInspection, } from "./managedArtifact.js"; @@ -14,7 +16,6 @@ import type { GraphBuildState, ParsedManagedGraphInput, } from "./managedApplicationGraph.js"; -import { moduleCoverageState } from "./managedApplicationGraphNodeCoverage.js"; type ManagedMethod = ManagedMemberInspection["methods"][number]; type ManagedField = ManagedMemberInspection["fields"][number]; type ManagedType = ManagedMemberInspection["types"][number]; @@ -44,7 +45,7 @@ export const addArtifactNode = (state: GraphBuildState): ApplicationNode => { format: "pe", source: "managed-application-graph", }, - evidence: managedEvidence(state, "project-managed-artifact"), + evidence: projectedManagedEvidence(state, "project-managed-artifact"), }, ], }); @@ -58,47 +59,48 @@ export const addArtifactIdentityNodes = ( artifactNode: ApplicationNode, parsed: ParsedManagedGraphInput, ): void => { - const artifact = parsed.artifact?.result; - const artifactCoverage = managedSourceCoverage( - parsed.artifact?.result.coverage.state ?? "complete", - ); - if (artifact?.assembly !== undefined && artifact.assembly !== null) { + const artifactInput = parsed.artifact; + if (artifactInput !== null && artifactInput.result.assembly !== null) { + const assemblyFacts = artifactInput.result.assembly; + const artifactEvidence = sourceManagedEvidence( + state, + artifactInput.evidence, + artifactInput.result.coverage.state, + ); const assembly = createJavaScriptApplicationNode({ kind: "managed-assembly", identity: artifactLocalIdentity( state.artifactSha256, "managed-assembly", - artifact.assembly.token, + assemblyFacts.token, ), observations: [ { - label: artifact.assembly.name, + label: assemblyFacts.name, properties: { - name: artifact.assembly.name, - version: artifact.assembly.version, - culture: artifact.assembly.culture, - public_key_kind: artifact.assembly.public_key.kind, + name: assemblyFacts.name, + version: assemblyFacts.version, + culture: assemblyFacts.culture, + public_key_kind: assemblyFacts.public_key.kind, }, - evidence: managedEvidence( - state, - "inspect_managed_artifact", - artifactCoverage, - ), + evidence: artifactEvidence, }, ], }); state.nodes.push(assembly); addContainsEdge(state, artifactNode, assembly, { kind: "declares-managed-assembly", - coverage: artifactCoverage, + coverage: artifactEvidence.coverage, }); } - const module = - artifact?.module ?? - parsed.members?.result.module ?? - parsed.boundaries?.result.module; - if (module !== undefined && module !== null) { - const moduleCoverage = managedSourceCoverage(moduleCoverageState(parsed)); + const moduleSource = selectModuleSource(parsed); + if (moduleSource !== null) { + const { module } = moduleSource; + const moduleEvidence = sourceManagedEvidence( + state, + moduleSource.evidence, + moduleSource.coverageState, + ); const moduleNode = createJavaScriptApplicationNode({ kind: "managed-module", identity: artifactLocalIdentity( @@ -115,36 +117,68 @@ export const addArtifactIdentityNodes = ( generation: module.generation, token: module.token, }, - evidence: managedEvidence( - state, - "inspect_managed_artifact", - moduleCoverage, - ), + evidence: moduleEvidence, }, ], }); state.nodes.push(moduleNode); addContainsEdge(state, artifactNode, moduleNode, { kind: "declares-managed-module", - coverage: moduleCoverage, + coverage: moduleEvidence.coverage, }); } }; +interface ManagedModuleSource { + readonly module: NonNullable; + readonly evidence: Evidence; + readonly coverageState: ManagedArtifactInspection["coverage"]["state"]; +} + +const selectModuleSource = ( + parsed: ParsedManagedGraphInput, +): ManagedModuleSource | null => { + if (parsed.artifact?.result.module != null) + return { + module: parsed.artifact.result.module, + evidence: parsed.artifact.evidence, + coverageState: parsed.artifact.result.coverage.state, + }; + if (parsed.members?.result.module != null) + return { + module: parsed.members.result.module, + evidence: parsed.members.evidence, + coverageState: parsed.members.result.coverage.state, + }; + if (parsed.boundaries?.result.module != null) + return { + module: parsed.boundaries.result.module, + evidence: parsed.boundaries.evidence, + coverageState: parsed.boundaries.result.coverage.state, + }; + return null; +}; + /** Add managed type, method, and field nodes from member evidence. */ export const addMemberNodes = ( state: GraphBuildState, artifactNode: ApplicationNode, parsed: ParsedManagedGraphInput, -) => { - const members = parsed.members?.result; - if (members === undefined) return { types: 0, methods: 0, fields: 0 }; +): void => { + const memberInput = parsed.members; + if (memberInput === null) return; + const members = memberInput.result; const { types, methods, fields } = members; const typeCoverage = managedSourceCoverage(members.coverage.state); const methodCoverage = managedSourceCoverage(members.coverage.state); const fieldCoverage = managedSourceCoverage(members.coverage.state); + const sourceEvidence = sourceManagedEvidence( + state, + memberInput.evidence, + members.coverage.state, + ); for (const type of types) { - const node = typeNode(state, type, typeCoverage); + const node = typeNode(state, type, sourceEvidence); state.nodes.push(node); state.typeNodes.set(type.token, node); addContainsEdge(state, artifactNode, node, { @@ -153,7 +187,7 @@ export const addMemberNodes = ( }); } for (const method of methods) { - const node = methodNode(state, method, methodCoverage); + const node = methodNode(state, method, sourceEvidence); state.nodes.push(node); state.methodNodes.set(method.token, node); const owner = @@ -166,7 +200,7 @@ export const addMemberNodes = ( }); } for (const field of fields) { - const node = fieldNode(state, field, fieldCoverage); + const node = fieldNode(state, field, sourceEvidence); state.nodes.push(node); state.fieldNodes.set(field.token, node); const owner = @@ -178,18 +212,13 @@ export const addMemberNodes = ( coverage: fieldCoverage, }); } - return { - types: types.length, - methods: methods.length, - fields: fields.length, - }; }; /** Build a managed type application node. */ const typeNode = ( state: GraphBuildState, type: ManagedType, - coverage: ApplicationGraphEvidence["coverage"], + evidence: ApplicationGraphEvidence, ): ApplicationNode => createJavaScriptApplicationNode({ kind: "managed-type", @@ -209,7 +238,7 @@ const typeNode = ( flags: type.flags, extends_token: type.extends_token, }, - evidence: managedEvidence(state, "inspect_managed_members", coverage), + evidence, }, ], }); @@ -218,7 +247,7 @@ const typeNode = ( const methodNode = ( state: GraphBuildState, method: ManagedMethod, - coverage: ApplicationGraphEvidence["coverage"], + evidence: ApplicationGraphEvidence, ): ApplicationNode => createJavaScriptApplicationNode({ kind: "managed-method", @@ -245,7 +274,7 @@ const methodNode = ( normalized_il_sha256: method.body.normalized_il_sha256, il_size: method.body.il_size, }, - evidence: managedEvidence(state, "inspect_managed_members", coverage), + evidence, }, ], }); @@ -254,7 +283,7 @@ const methodNode = ( const fieldNode = ( state: GraphBuildState, field: ManagedField, - coverage: ApplicationGraphEvidence["coverage"], + evidence: ApplicationGraphEvidence, ): ApplicationNode => createJavaScriptApplicationNode({ kind: "managed-field", @@ -278,7 +307,7 @@ const fieldNode = ( signature_sha256: field.signature.raw_sha256, signature_status: field.signature.parse_status, }, - evidence: managedEvidence(state, "inspect_managed_members", coverage), + evidence, }, ], }); @@ -288,23 +317,33 @@ export const addBoundaryNodes = ( state: GraphBuildState, artifactNode: ApplicationNode, parsed: ParsedManagedGraphInput, -) => { - const boundaries = parsed.boundaries?.result; - if (boundaries === undefined) - return { pinvoke_imports: 0, native_implementations: 0 }; +): void => { + const boundaryInput = parsed.boundaries; + if (boundaryInput === null) return; + const boundaries = boundaryInput.result; const { pinvoke_imports: pinvokes, native_implementations: implementations } = boundaries; const pinvokeCoverage = managedSourceCoverage(boundaries.coverage.state); const implementationCoverage = managedSourceCoverage( boundaries.coverage.state, ); + const sourceEvidence = sourceManagedEvidence( + state, + boundaryInput.evidence, + boundaries.coverage.state, + ); for (const pinvoke of pinvokes) { - const node = pinvokeNode(state, pinvoke, pinvokeCoverage); + const node = pinvokeNode(state, pinvoke, sourceEvidence); state.nodes.push(node); - const owner = + const method = pinvoke.member_token === null - ? artifactNode - : (state.methodNodes.get(pinvoke.member_token) ?? artifactNode); + ? undefined + : state.methodNodes.get(pinvoke.member_token); + const memberEvidence = + method === undefined || parsed.members === null + ? undefined + : parsed.members.evidence; + const owner = method ?? artifactNode; state.edges.push( createJavaScriptApplicationEdge({ source_node_id: owner.node_id, @@ -315,10 +354,11 @@ export const addBoundaryNodes = ( import_name: pinvoke.import_name, import_scope_name: pinvoke.import_scope_name, }, - evidence: managedEvidence( + evidence: pinvokeAssociationEvidence( state, - "inspect_managed_native_boundaries", + boundaryInput.evidence, pinvokeCoverage, + memberEvidence, ), }), ); @@ -327,7 +367,7 @@ export const addBoundaryNodes = ( const node = nativeImplementationNode( state, implementation, - implementationCoverage, + sourceEvidence, ); state.nodes.push(node); const owner = state.methodNodes.get(implementation.token) ?? artifactNode; @@ -336,17 +376,13 @@ export const addBoundaryNodes = ( coverage: implementationCoverage, }); } - return { - pinvoke_imports: pinvokes.length, - native_implementations: implementations.length, - }; }; /** Build a managed P/Invoke import application node. */ const pinvokeNode = ( state: GraphBuildState, pinvoke: PinvokeImport, - coverage: ApplicationGraphEvidence["coverage"], + evidence: ApplicationGraphEvidence, ): ApplicationNode => createJavaScriptApplicationNode({ kind: "managed-pinvoke-import", @@ -368,11 +404,7 @@ const pinvokeNode = ( call_convention: pinvoke.call_convention, verification: pinvoke.verification, }, - evidence: managedEvidence( - state, - "inspect_managed_native_boundaries", - coverage, - ), + evidence, }, ], }); @@ -381,7 +413,7 @@ const pinvokeNode = ( const nativeImplementationNode = ( state: GraphBuildState, implementation: NativeImplementation, - coverage: ApplicationGraphEvidence["coverage"], + evidence: ApplicationGraphEvidence, ): ApplicationNode => createJavaScriptApplicationNode({ kind: "managed-native-implementation", @@ -403,11 +435,7 @@ const nativeImplementationNode = ( boundary_kind: implementation.boundary_kind, body_interpretation: implementation.body_interpretation, }, - evidence: managedEvidence( - state, - "inspect_managed_native_boundaries", - coverage, - ), + evidence, }, ], }); @@ -425,7 +453,7 @@ const addContainsEdge = ( target_node_id: target.node_id, relation: "contains", properties: { kind: options.kind }, - evidence: managedEvidence( + evidence: projectedManagedEvidence( state, "project-managed-contains", options.coverage, @@ -448,12 +476,43 @@ const artifactLocalIdentity = ( }); /** Build managed static-analysis evidence for a graph observation. */ -const managedEvidence = ( +const sourceManagedEvidence = ( + state: GraphBuildState, + source: Evidence, + coverageState: ManagedArtifactInspection["coverage"]["state"], +): ApplicationGraphEvidence => + createManagedEvidence( + state, + source.operation, + managedSourceCoverage(coverageState), + [source.evidence_id], + ); + +const projectedManagedEvidence = ( state: GraphBuildState, operation: string, coverage: ApplicationGraphEvidence["coverage"] = managedSourceCoverage( "complete", ), +): ApplicationGraphEvidence => + createManagedEvidence(state, operation, coverage, state.evidenceLinks); + +const pinvokeAssociationEvidence = ( + state: GraphBuildState, + boundaryEvidence: Evidence, + coverage: ApplicationGraphEvidence["coverage"], + memberEvidence: Evidence | undefined, +): ApplicationGraphEvidence => + createManagedEvidence(state, boundaryEvidence.operation, coverage, [ + boundaryEvidence.evidence_id, + ...(memberEvidence === undefined ? [] : [memberEvidence.evidence_id]), + ]); + +const createManagedEvidence = ( + state: GraphBuildState, + operation: string, + coverage: ApplicationGraphEvidence["coverage"], + evidenceIds: readonly string[], ): ApplicationGraphEvidence => ({ authority: "managed-static-analysis", state: "observed", @@ -483,7 +542,7 @@ const managedEvidence = ( : [ "The source managed Evidence slice is incomplete; unreturned or unavailable items remain unobserved.", ], - evidence_ids: state.evidenceLinks, + evidence_ids: [...evidenceIds], }); /** Sanitize an artifact path into a managed graph location. */ diff --git a/tests/composition/analysis-sessions/managedApplicationGraph.test.ts b/tests/composition/analysis-sessions/managedApplicationGraph.test.ts index 39d31b07b..22eed0b21 100644 --- a/tests/composition/analysis-sessions/managedApplicationGraph.test.ts +++ b/tests/composition/analysis-sessions/managedApplicationGraph.test.ts @@ -16,43 +16,51 @@ import { managedPeFixtureTarget, } from "../../../src/dotnet/ManagedPe.fixture.js"; -describe("managed application graph projection", () => { - it("projects managed metadata and native declarations into authenticated graph Evidence", () => { - const bytes = buildManagedPeFixture({ - pinvoke: { - moduleName: "user32.dll", - importName: "MessageBoxW", - mappingFlags: 0x0345, - }, - }); - const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe"); - const managedArtifact = inspectManagedArtifactBytes(bytes, binary); - const members = inspectManagedMembersBytes(bytes, binary); - const boundaries = inspectManagedNativeBoundariesBytes(bytes, binary); - const artifactEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { +const createManagedInteropEvidence = () => { + const bytes = buildManagedPeFixture({ + pinvoke: { + moduleName: "user32.dll", + importName: "MessageBoxW", + mappingFlags: 0x0345, + }, + }); + const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe"); + const managedArtifact = inspectManagedArtifactBytes(bytes, binary); + const members = inspectManagedMembersBytes(bytes, binary); + const boundaries = inspectManagedNativeBoundariesBytes(bytes, binary); + + return { + artifactEvidence: createEvidence(binary, MANAGED_STATIC_PROVIDER, { operation: "inspect_managed_artifact", parameters: {}, result: managedArtifact, rawResult: null, limitations: managedArtifact.limitations, locations: [{ kind: "artifact-path", path: binary.path }], - }); - const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { + }), + memberEvidence: createEvidence(binary, MANAGED_STATIC_PROVIDER, { operation: "inspect_managed_members", parameters: {}, result: members, rawResult: null, limitations: members.limitations, locations: [{ kind: "artifact-path", path: binary.path }], - }); - const boundaryEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { + }), + boundaryEvidence: createEvidence(binary, MANAGED_STATIC_PROVIDER, { operation: "inspect_managed_native_boundaries", parameters: {}, result: boundaries, rawResult: null, limitations: boundaries.limitations, locations: [{ kind: "artifact-path", path: binary.path }], - }); + }), + }; +}; + +describe("managed application graph projection", () => { + it("projects managed metadata and native declarations into authenticated graph Evidence", () => { + const { artifactEvidence, memberEvidence, boundaryEvidence } = + createManagedInteropEvidence(); const evidence = projectManagedApplicationGraphEvidence({ managed_artifact: artifactEvidence, @@ -103,21 +111,51 @@ describe("managed application graph projection", () => { "managed-pinvoke-import", ]), ); + const allEvidenceIds = [ + artifactEvidence.evidence_id, + memberEvidence.evidence_id, + boundaryEvidence.evidence_id, + ].sort(); + const observedEvidenceIds = (kind: string): readonly string[] => { + const observation = graph.nodes.find((node) => node.kind === kind) + ?.observations[0]; + if (observation === undefined) + throw new Error(`Expected ${kind} observation`); + return observation.evidence.evidence_ids; + }; + expect(observedEvidenceIds("artifact")).toEqual(allEvidenceIds); + expect(observedEvidenceIds("managed-assembly")).toEqual([ + artifactEvidence.evidence_id, + ]); + expect(observedEvidenceIds("managed-module")).toEqual([ + artifactEvidence.evidence_id, + ]); + for (const kind of ["managed-type", "managed-method", "managed-field"]) + expect(observedEvidenceIds(kind)).toEqual([memberEvidence.evidence_id]); + expect(observedEvidenceIds("managed-pinvoke-import")).toEqual([ + boundaryEvidence.evidence_id, + ]); + for (const edge of graph.edges.filter( + ({ relation }) => relation === "contains", + )) + expect(edge.evidence.evidence_ids).toEqual(allEvidenceIds); const method = graph.nodes.find( ({ kind, observations }) => kind === "managed-method" && observations[0]?.label === "Fixture.Program.Main", ); expect(method).toBeDefined(); - expect( - graph.edges.some( - ({ source_node_id, relation, target_node_id }) => - source_node_id === method?.node_id && - relation === "imports" && - graph.nodes.find(({ node_id: id }) => id === target_node_id)?.kind === - "managed-pinvoke-import", - ), - ).toBe(true); + const importEdge = graph.edges.find( + ({ source_node_id, relation, target_node_id }) => + source_node_id === method?.node_id && + relation === "imports" && + graph.nodes.find(({ node_id: id }) => id === target_node_id)?.kind === + "managed-pinvoke-import", + ); + expect(importEdge).toBeDefined(); + expect(importEdge?.evidence.evidence_ids).toEqual( + [memberEvidence.evidence_id, boundaryEvidence.evidence_id].sort(), + ); expect( graph.nodes.flatMap(({ observations }) => observations.map(({ evidence }) => evidence.authority), @@ -167,7 +205,7 @@ describe("managed application graph request", () => { }); describe("managed application graph coverage", () => { - it("rejects managed Evidence digest mismatch and discloses missing artifact observations", () => { + it("rejects managed Evidence whose artifact digest differs from its subject", () => { const bytes = buildManagedPeFixture(); const binary = managedPeFixtureTarget(bytes, "/fixture/Mismatch.dll"); const members = inspectManagedMembersBytes(bytes, binary); @@ -191,7 +229,14 @@ describe("managed application graph coverage", () => { expect(JSON.stringify(rejected.error)).toContain( `Managed Evidence inspect_managed_members (${mismatched.evidence_id}) subject SHA-256 ${binary.sha256} does not match normalized artifact SHA-256 ${"b".repeat(64)}`, ); + }); +}); +describe("managed application graph identity facts", () => { + it("uses member Evidence for its module and reports only emitted identity nodes", () => { + const bytes = buildManagedPeFixture(); + const binary = managedPeFixtureTarget(bytes, "/fixture/MembersOnly.dll"); + const members = inspectManagedMembersBytes(bytes, binary); const aligned = createEvidence(binary, MANAGED_STATIC_PROVIDER, { operation: "inspect_managed_members", parameters: {}, @@ -204,11 +249,92 @@ describe("managed application graph coverage", () => { const result = managedApplicationGraphResultSchema.parse( parseEvidence(projected.value).normalized_result, ); + const graph = parseJavaScriptApplicationGraph(result.graph); + expect(result.summary).toMatchObject({ assemblies: 0, modules: 1 }); + expect( + graph.nodes.find(({ kind }) => kind === "managed-module") + ?.observations[0], + ).toMatchObject({ + evidence: { + extractor: { operation: "inspect_managed_members" }, + evidence_ids: [aligned.evidence_id], + }, + }); + expect(result.evidence_links).toEqual([aligned.evidence_id]); expect(result.limitations).toContain( "Managed artifact Evidence was not supplied; assembly identity observations are absent.", ); }); + it("binds a boundaries-only module node to the boundary Evidence that supplied it", () => { + const bytes = buildManagedPeFixture(); + const binary = managedPeFixtureTarget(bytes, "/fixture/BoundariesOnly.dll"); + const boundaries = inspectManagedNativeBoundariesBytes(bytes, binary); + const boundaryEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { + operation: "inspect_managed_native_boundaries", + parameters: {}, + result: boundaries, + rawResult: null, + limitations: boundaries.limitations, + locations: [{ kind: "artifact-path", path: binary.path }], + }); + + const projected = projectManagedApplicationGraphEvidence({ + managed_native_boundaries: boundaryEvidence, + }); + if (!projected.ok) throw projected.error; + const result = managedApplicationGraphResultSchema.parse( + parseEvidence(projected.value).normalized_result, + ); + const graph = parseJavaScriptApplicationGraph(result.graph); + expect(result.summary).toMatchObject({ assemblies: 0, modules: 1 }); + expect( + graph.nodes.find(({ kind }) => kind === "managed-module") + ?.observations[0], + ).toMatchObject({ + evidence: { + extractor: { operation: "inspect_managed_native_boundaries" }, + evidence_ids: [boundaryEvidence.evidence_id], + }, + }); + expect(result.evidence_links).toEqual([boundaryEvidence.evidence_id]); + }); + + it("reports no assembly or module when the inspector observes no identity rows", () => { + const bytes = buildManagedPeFixture({ + moduleRowCount: 0, + assemblyRowCount: 0, + }); + const binary = managedPeFixtureTarget(bytes, "/fixture/NoIdentityRows.exe"); + const inspection = inspectManagedArtifactBytes(bytes, binary); + expect(inspection).toMatchObject({ module: null, assembly: null }); + const artifactEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { + operation: "inspect_managed_artifact", + parameters: {}, + result: inspection, + rawResult: null, + limitations: inspection.limitations, + locations: [{ kind: "artifact-path", path: binary.path }], + }); + + const projected = projectManagedApplicationGraphEvidence({ + managed_artifact: artifactEvidence, + }); + if (!projected.ok) throw projected.error; + const result = managedApplicationGraphResultSchema.parse( + parseEvidence(projected.value).normalized_result, + ); + const graph = parseJavaScriptApplicationGraph(result.graph); + expect(result.summary).toMatchObject({ assemblies: 0, modules: 0 }); + expect( + graph.nodes.filter( + ({ kind }) => kind === "managed-assembly" || kind === "managed-module", + ), + ).toEqual([]); + }); +}); + +describe("managed application graph coverage", () => { it("preserves partial parser coverage in graph and per-fact coverage", () => { const bytes = buildManagedPeFixture(); const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe"); From 07675f78c66ce9e8706e808d417265e18ba9f3a5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:13:57 +0800 Subject: [PATCH 009/189] fix(ghidra): retain process ownership after failed launch rollback --- src/ghidra/GhidraClient.ts | 23 +++- src/ghidra/GhidraLauncher.ts | 88 +++++++++---- .../providers/ghidra/ghidraClient.test.ts | 124 +++++++++++++++++- 3 files changed, 206 insertions(+), 29 deletions(-) diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 71c5a9357..33c5add1b 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -25,7 +25,7 @@ import type { import type { GhidraInventoryOperation } from "./GhidraInventoryValues.js"; import type { GhidraFunctionOperation } from "./GhidraFunctionValues.js"; import { createGhidraDiagnostics } from "./GhidraDiagnostics.js"; -import type { GhidraLaunch } from "./GhidraLauncher.js"; +import { GhidraLaunchError, type GhidraLaunch } from "./GhidraLauncher.js"; import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js"; import { GhidraResponseRouter } from "./GhidraResponseRouter.js"; import { GhidraRequestQueue } from "./GhidraRequestQueue.js"; @@ -425,8 +425,18 @@ export class GhidraClient { err(this.#failure("start", "Ghidra launcher failed", cause)), ); if (!launched.ok) { + const partialLaunch = + launched.error instanceof GhidraLaunchError + ? launched.error.partialLaunch + : undefined; + if (partialLaunch !== undefined) { + this.#launch = partialLaunch; + this.#process = new ProviderProcessSupervisor(partialLaunch, { + onDiagnostic: (event) => this.#onProcessDiagnostic(event), + }); + } const failure = deadline.signal.aborted - ? this.#interruptionFailure(deadline) + ? this.#interruptionFailure(deadline, launched.error) : launched.error instanceof GhidraSessionError ? launched.error : this.#failure("start", launched.error.message, launched.error); @@ -699,10 +709,13 @@ export class GhidraClient { return this.#startupFailure(failure); } - #interruptionFailure(deadline: ProviderStartupDeadline): GhidraSessionError { + #interruptionFailure( + deadline: ProviderStartupDeadline, + cause?: unknown, + ): GhidraSessionError { return deadline.interruption === "cancelled" - ? this.#failure("cancelled", "Ghidra startup was cancelled") - : this.#failure("timeout", "Ghidra startup deadline elapsed", undefined, { + ? this.#failure("cancelled", "Ghidra startup was cancelled", cause) + : this.#failure("timeout", "Ghidra startup deadline elapsed", cause, { timeoutMs: deadline.timeoutMs, }); } diff --git a/src/ghidra/GhidraLauncher.ts b/src/ghidra/GhidraLauncher.ts index b31262fd6..73bf05627 100644 --- a/src/ghidra/GhidraLauncher.ts +++ b/src/ghidra/GhidraLauncher.ts @@ -56,9 +56,21 @@ export interface GhidraLauncher { /** Local launch failure retained as the cause of a provider-neutral error. */ export class GhidraLaunchError extends Error { - constructor(message: string, options?: ErrorOptions) { - super(message, options); + readonly #partialLaunch: GhidraLaunch | undefined; + + constructor( + message: string, + options?: ErrorOptions & { readonly partialLaunch?: GhidraLaunch }, + ) { + const { partialLaunch, ...errorOptions } = options ?? {}; + super(message, errorOptions); this.name = "GhidraLaunchError"; + this.#partialLaunch = partialLaunch; + } + + /** Process ownership retained for the client to retry an incomplete rollback. */ + get partialLaunch(): GhidraLaunch | undefined { + return this.#partialLaunch; } } @@ -74,6 +86,8 @@ export interface GhidraHeadlessLauncherOptions { readonly dosMz?: true; readonly dosCom?: true; readonly analysisExtensions?: readonly GhidraExtension[]; + /** Spawn seam for provider-boundary lifecycle tests. */ + readonly spawnProcess?: typeof spawnOwnedProviderProcess; } /** Launch Ghidra without copying scripts into or modifying its installation. */ @@ -168,7 +182,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { : { signal: options.signal }), }) : { ...scriptCommand, environment }; - started = await spawnOwnedProviderProcess({ + started = await (this.options.spawnProcess ?? spawnOwnedProviderProcess)({ command: command.command, arguments: command.arguments, runId: session.runId, @@ -181,6 +195,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { hostEnvironment: {}, ...(options.signal === undefined ? {} : { signal: options.signal }), }); + const partialLaunch = ownedGhidraLaunch(started, paths, platform); await writeGhidraRuntimeFile( paths.ownershipPath, `${JSON.stringify({ @@ -199,33 +214,60 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { platform, ); if (isAborted(options.signal)) { - await cleanupStartedProcess(started, platform); - return err(new AnalysisCancelledError("open_binary")); + throw new AnalysisCancelledError("open_binary"); } - const spawned = started; - return ok({ - ...ownedGhidraProcess(spawned, platform), - projectRoot: paths.projectRoot, - ghidraLogPath: paths.ghidraLogPath, - scriptLogPath: paths.scriptLogPath, - }); + return ok(partialLaunch); } catch (cause: unknown) { - if (started !== undefined) - await cleanupStartedProcess(started, platform).catch( - (cause: unknown) => { - // best-effort cleanup: started-process cleanup must not mask the launch failure. - void cause; - }, - ); - return isAborted(options.signal) - ? err(new AnalysisCancelledError("open_binary")) - : err( - new GhidraLaunchError("Ghidra headless launch failed", { cause }), + const primary = isAborted(options.signal) + ? new AnalysisCancelledError("open_binary", { cause }) + : new GhidraLaunchError("Ghidra headless launch failed", { cause }); + if (started === undefined) return err(primary); + + let cleanupFailure: unknown; + try { + const cleanup = await cleanupStartedProcess(started, platform); + if (!cleanup.cleaned) + cleanupFailure = new Error( + `Ghidra process cleanup was incomplete: ${cleanup.reason}`, ); + } catch (failure: unknown) { + cleanupFailure = failure; + } + if (cleanupFailure !== undefined) { + const partialLaunch = ownedGhidraLaunch(started, paths, platform); + const primaryMessage = isAborted(options.signal) + ? primary.message + : `Ghidra headless launch failed: ${cause instanceof Error ? cause.message : String(cause)}`; + return err( + new GhidraLaunchError( + `${primaryMessage}; process cleanup remains incomplete`, + { + cause: new AggregateError( + [primary, cleanupFailure], + "Ghidra launch rollback did not release its process", + { cause: primary }, + ), + partialLaunch, + }, + ), + ); + } + return err(primary); } } } +const ownedGhidraLaunch = ( + spawned: SpawnedOwnedProviderProcess, + paths: ReturnType, + platform: NodeJS.Platform, +): GhidraLaunch => ({ + ...ownedGhidraProcess(spawned, platform), + projectRoot: paths.projectRoot, + ghidraLogPath: paths.ghidraLogPath, + scriptLogPath: paths.scriptLogPath, +}); + const ownedGhidraProcess = ( spawned: SpawnedOwnedProviderProcess, platform: NodeJS.Platform, diff --git a/tests/boundary/providers/ghidra/ghidraClient.test.ts b/tests/boundary/providers/ghidra/ghidraClient.test.ts index ed60ccf90..a8a7eeac8 100644 --- a/tests/boundary/providers/ghidra/ghidraClient.test.ts +++ b/tests/boundary/providers/ghidra/ghidraClient.test.ts @@ -1,7 +1,7 @@ import { spawn, type ChildProcess } from "node:child_process"; import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; -import { access, chmod, mkdir } from "node:fs/promises"; +import { access, chmod, mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -11,6 +11,7 @@ import type { Logger } from "pino"; import { ok } from "../../../../src/domain/result.js"; import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js"; +import { GhidraHeadlessLauncher } from "../../../../src/ghidra/GhidraLauncher.js"; import type { GhidraDiagnostic } from "../../../../src/ghidra/GhidraClientTypes.js"; import type { GhidraLaunchSession, @@ -19,6 +20,7 @@ import type { import type { GhidraTransportKind } from "../../../../src/ghidra/GhidraTransport.js"; import { GHIDRA_SESSION_CAPABILITIES } from "../../../../src/ghidra/GhidraSessionValues.js"; import { waitForExit as waitForChildExit } from "../../../support/process/processFixture.js"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; const fixturePath = fileURLToPath( new URL("../../../fixtures/fakeGhidra.mjs", import.meta.url), @@ -743,3 +745,123 @@ it("preserves failed startup and retained Ghidra cleanup capabilities until a ve expect(cleanupAttempts).toBe(3); await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); }); + +describe.skipIf(process.platform === "win32")( + "Ghidra launcher rollback ownership", + () => { + it.each([ + ["ownership manifest write failure", false, "start"], + ["cancellation after process creation", true, "cancelled"], + ] as const)( + "retains the original process and runtime roots after %s until cleanup succeeds", + async (failureMode, cancelAfterSpawn, expectedKind) => { + const root = await createTestTempDirectory("rea-ghidra-rollback-"); + const java = join(root, "jdk", "bin", "java"); + await mkdir(join(root, "jdk", "bin"), { recursive: true }); + await writeFile( + java, + "#!/usr/bin/env node\n// LaunchSupport fixture emits no optional values.\n", + ); + await chmod(java, 0o755); + + const controller = new AbortController(); + let cleanupAllowed = false; + let cleanupAttempts = 0; + let child: ChildProcess | undefined; + let runtimeRoot: string | undefined; + const headless = new GhidraHeadlessLauncher({ + environment: process.env, + javaHome: join(root, "jdk"), + analyzeHeadlessPath: "/unused/ghidra/support/analyzeHeadless", + bridgeScriptPath: "/unused/rea/ReaGhidraBridge.java", + spawnProcess: async ({ runId }) => { + const spawned = spawn( + process.execPath, + ["-e", "setInterval(() => {}, 1000)"], + { detached: true, stdio: ["ignore", "pipe", "pipe"] }, + ); + child = spawned; + await new Promise((resolve, reject) => { + spawned.once("spawn", () => resolve()); + spawned.once("error", reject); + }); + if (cancelAfterSpawn) + controller.abort(new Error("rollback cancellation fixture")); + const pid = spawned.pid; + if (pid === undefined) throw new Error("fixture child has no PID"); + return { + process: spawned, + ownership: { + runId, + leaderPid: pid, + processGroupId: pid, + expectedParentPid: process.pid, + }, + cleanup: async () => { + cleanupAttempts += 1; + if (!cleanupAllowed) + return { + cleaned: false as const, + reason: `${failureMode} cleanup is still unavailable`, + }; + if (spawned.exitCode === null && spawned.signalCode === null) + spawned.kill("SIGTERM"); + const exited = await waitForChildExit(spawned, 5_000); + return exited + ? { cleaned: true as const, signaled: true } + : { + cleaned: false as const, + reason: "fixture child did not exit", + }; + }, + }; + }, + }); + const launcher: GhidraLauncher = { + async launch(session, options) { + runtimeRoot = session.runtimeRoot; + if (!cancelAfterSpawn) + await mkdir(join(session.runtimeRoot, "ownership.json")); + return headless.launch(session, options); + }, + }; + const client = clientFor(launcher); + onTestFinished(async () => { + cleanupAllowed = true; + await client.close(); + }); + + const started = await client.start( + cancelAfterSpawn ? controller.signal : undefined, + ); + expect(started).toMatchObject({ + ok: false, + error: { + kind: expectedKind, + cleanupFailure: { cleanupIncomplete: true }, + }, + }); + if (started.ok) throw new Error("expected startup rollback failure"); + expect(started.error.message).toContain( + cancelAfterSpawn ? "startup was cancelled" : "headless launch failed", + ); + if (!cancelAfterSpawn) + expect(started.error.message).toContain("ownership.json"); + if (runtimeRoot === undefined || child === undefined) + throw new Error("fixture did not retain the started process owner"); + await access(runtimeRoot); + expect(child.exitCode).toBeNull(); + expect(child.signalCode).toBeNull(); + expect(cleanupAttempts).toBe(2); + + cleanupAllowed = true; + await expect(client.close()).resolves.toEqual(ok(null)); + expect(cleanupAttempts).toBe(3); + await expect(access(runtimeRoot)).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect(waitForExit(child)).resolves.toBe(true); + }, + ); + }, +); From 44c92f88c51841735741811a68cc89fde14efa80 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:14:14 +0800 Subject: [PATCH 010/189] refactor: remove obsolete source exclusions and identity wrapper --- src/artifacts/ArtifactProvider.ts | 5 +---- src/artifacts/inventory/policy.ts | 11 ----------- src/domain/referenceSourceGraph.ts | 2 -- src/domain/referenceSourcePolicy.ts | 2 +- 4 files changed, 2 insertions(+), 18 deletions(-) delete mode 100644 src/artifacts/inventory/policy.ts diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index c8ed381ee..e4b514a4f 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -39,7 +39,6 @@ import { } from "./ArtifactProviderMetadata.js"; import { createEvidence } from "../domain/evidence.js"; import { createArtifactInspection } from "../domain/artifactInspection.js"; -import { resolveArtifactIntegrityPolicy } from "./inventory/policy.js"; /** Read-only inventory and exclusively owned extraction provider. */ export class ArtifactProvider implements AnalysisProvider { @@ -364,9 +363,7 @@ class ArtifactClient implements AnalysisClient { return inventoryArtifact(this.target.sourcePath ?? this.target.path, { environment: this.environment, ...(options?.signal === undefined ? {} : { signal: options.signal }), - integrity: resolveArtifactIntegrityPolicy({ - mode: parsed.integrity_policy, - }), + integrity: { mode: parsed.integrity_policy }, }); } } diff --git a/src/artifacts/inventory/policy.ts b/src/artifacts/inventory/policy.ts deleted file mode 100644 index f2eddd0f8..000000000 --- a/src/artifacts/inventory/policy.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { ArtifactIntegrityPolicy } from "./types.js"; - -/** Parsed caller intent for integrity mismatch handling. */ -export type ArtifactIntegrityIntent = - | { readonly mode: "fail" } - | { readonly mode: "record-and-continue" }; - -/** Preserve the explicit integrity admission choice without changing verification. */ -export const resolveArtifactIntegrityPolicy = ( - intent: ArtifactIntegrityIntent, -): ArtifactIntegrityPolicy => intent; diff --git a/src/domain/referenceSourceGraph.ts b/src/domain/referenceSourceGraph.ts index 1e8c3d782..080f674a2 100644 --- a/src/domain/referenceSourceGraph.ts +++ b/src/domain/referenceSourceGraph.ts @@ -133,8 +133,6 @@ const exclusionSchema = z.strictObject({ reason: z.enum([ "configured-secret", "symlink-escape", - "size-limit", - "inventory-limit", "unreadable", "caller-excluded", ]), diff --git a/src/domain/referenceSourcePolicy.ts b/src/domain/referenceSourcePolicy.ts index e9c9cf323..204728249 100644 --- a/src/domain/referenceSourcePolicy.ts +++ b/src/domain/referenceSourcePolicy.ts @@ -1,4 +1,4 @@ -/** Exclusions and maximum traversal sizes for historical source imports. */ +/** Caller-selected path exclusions for historical source imports. */ export interface ReferenceSourcePolicy { readonly secretPatterns: readonly string[]; } From f3c4a332f7bd198bd67f0187bc2a85c7b31bb960 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:16:04 +0800 Subject: [PATCH 011/189] fix(targets): cancel resolution before provider admission --- scripts/lib/ghidra-reference-snapshot-e2e.mjs | 9 +- src/application/BinaryTargetResolver.ts | 75 ++++++++-- src/application/DirectAnalysis.ts | 15 +- src/application/Doctor.ts | 23 +++- .../android/AndroidAnalysisService.ts | 4 +- src/application/binary/BinarySessionOpen.ts | 16 ++- .../boundary/filesystem/binaryTarget.test.ts | 128 ++++++++++++++---- .../boundary/filesystem/dosComTarget.test.ts | 25 ++-- .../boundary/process/jadxIntegration.test.ts | 26 +++- 9 files changed, 244 insertions(+), 77 deletions(-) diff --git a/scripts/lib/ghidra-reference-snapshot-e2e.mjs b/scripts/lib/ghidra-reference-snapshot-e2e.mjs index b0ce2318f..7a99099b6 100644 --- a/scripts/lib/ghidra-reference-snapshot-e2e.mjs +++ b/scripts/lib/ghidra-reference-snapshot-e2e.mjs @@ -51,11 +51,10 @@ export async function verifyLegacyGhidraReferenceSnapshot( legacyParameters, ); assert.notEqual(legacyProfile.digest, observed.analysis_profile.digest); - const parsed = await parseBinaryTarget( - target.path, - process.cwd(), - process.arch, - ); + const parsed = await parseBinaryTarget(target.path, { + cwd: process.cwd(), + hostArchitecture: process.arch, + }); if (!parsed.ok) throw parsed.error; const nativeTarget = parsed.value; const result = structuredClone(observed.normalized_result); diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 24fb5358f..f45a1d9a6 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -10,6 +10,7 @@ import { import { extname, isAbsolute, resolve } from "node:path"; import { BinaryTargetError } from "../domain/configurationErrors.js"; +import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { err, ok, type Result } from "../domain/result.js"; import { @@ -32,6 +33,15 @@ import { type ExecutableMetadata, } from "../domain/binaryTarget.js"; +/** Options for resolving a local binary target and its stable identity. */ +export interface BinaryTargetResolverOptions { + readonly cwd?: string; + readonly hostArchitecture?: NodeJS.Architecture; + readonly targetKind?: BinaryTarget["kind"]; + readonly formatHint?: ExecutableFormatHint; + readonly signal?: AbortSignal; +} + /** * Resolve and classify a readable local target before a provider is selected. * FAT Mach-O inputs select only a host-compatible architecture so setup remains @@ -39,24 +49,32 @@ import { */ export const parseBinaryTarget = async ( input: string, - cwd = process.cwd(), - hostArchitecture: NodeJS.Architecture = process.arch, - targetKind?: BinaryTarget["kind"], - formatHint?: ExecutableFormatHint, -): Promise> => { + options: BinaryTargetResolverOptions = {}, +): Promise< + Result +> => { + const cwd = options.cwd ?? process.cwd(); + const hostArchitecture = options.hostArchitecture ?? process.arch; + const { targetKind, formatHint, signal } = options; const candidate = isAbsolute(input) ? input : resolve(cwd, input); try { + throwIfTargetResolutionCancelled(signal); await access(candidate, constants.R_OK); + throwIfTargetResolutionCancelled(signal); const canonical = await realpath(candidate); + throwIfTargetResolutionCancelled(signal); const resolved = await resolveAppBundle(canonical); + throwIfTargetResolutionCancelled(signal); if (!resolved.ok) return err(resolved.error); const { executable: path, infoPlist } = resolved.value; const bundle = infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist }; const handle = await open(path, "r"); try { + throwIfTargetResolutionCancelled(signal); if (!(await handle.stat()).isFile()) return err(new BinaryTargetError(path, "target is not a regular file")); + throwIfTargetResolutionCancelled(signal); if (formatHint === "dos-com") { if (targetKind !== undefined && targetKind !== "executable") return err( @@ -70,7 +88,7 @@ export const parseBinaryTarget = async ( return ok({ path, sourcePath: canonical, - sha256: await sha256Handle(handle), + sha256: await sha256Handle(handle, signal), kind: "executable", format: "dos-com", architecture: "x86", @@ -84,28 +102,32 @@ export const parseBinaryTarget = async ( return ok({ path, sourcePath: process.platform === "win32" ? candidate : canonical, - sha256: await sha256Handle(handle), + sha256: await sha256Handle(handle, signal), kind: "database", format: "analysis-database", }); - const artifactFormat = await detectArtifactFormat(path, handle); + const artifactFormat = await detectArtifactFormat(path, handle, signal); if (artifactFormat !== undefined) { const identity = { path, sourcePath: process.platform === "win32" ? candidate : canonical, - sha256: await sha256Handle(handle), + sha256: await sha256Handle(handle, signal), }; return isArchiveFormat(artifactFormat) ? ok({ ...identity, kind: "archive", format: artifactFormat }) : ok({ ...identity, kind: "artifact", format: artifactFormat }); } - const detected = await readExecutableMetadata(handle, hostArchitecture); + const detected = await readExecutableMetadata( + handle, + hostArchitecture, + signal, + ); if (!detected.ok) return err(new BinaryTargetError(path, detected.error)); return ok({ path, sourcePath: process.platform === "win32" ? candidate : canonical, ...bundle, - sha256: await sha256Handle(handle), + sha256: await sha256Handle(handle, signal), kind: "executable", ...detected.value, }); @@ -113,6 +135,7 @@ export const parseBinaryTarget = async ( await handle.close(); } } catch (cause: unknown) { + if (cause instanceof AnalysisCancelledError) return err(cause); if (!(cause instanceof Error)) throw cause; const code = filesystemErrorCode(cause); if (code === undefined) throw cause; @@ -146,9 +169,15 @@ const targetFailureReason = (code: string, detail: string): string => { } }; +const throwIfTargetResolutionCancelled = (signal?: AbortSignal): void => { + if (signal?.aborted === true) + throw new AnalysisCancelledError("resolve_binary_target"); +}; + const detectArtifactFormat = async ( path: string, handle: FileHandle, + signal?: AbortSignal, ): Promise< | Exclude< BinaryTarget["format"], @@ -156,9 +185,11 @@ const detectArtifactFormat = async ( > | undefined > => { + throwIfTargetResolutionCancelled(signal); const lower = path.toLowerCase(); const magic = Buffer.alloc(8); const observed = await handle.read(magic, 0, magic.length, 0); + throwIfTargetResolutionCancelled(signal); if (hasZipSignature(magic.subarray(0, observed.bytesRead))) { return zipPackageFormatForPath(lower) ?? "zip"; } @@ -171,10 +202,13 @@ const detectArtifactFormat = async ( ) return "pkg"; if (lower.endsWith(".dmg")) { + throwIfTargetResolutionCancelled(signal); const size = (await handle.stat()).size; + throwIfTargetResolutionCancelled(signal); if (size >= 512) { const trailer = Buffer.alloc(4); const read = await handle.read(trailer, 0, trailer.length, size - 512); + throwIfTargetResolutionCancelled(signal); if (read.bytesRead === 4 && trailer.toString("ascii") === "koly") return "dmg"; } @@ -199,12 +233,17 @@ const isArchiveFormat = ( ): format is Extract["format"] => ["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format); -const sha256Handle = async (handle: FileHandle): Promise => { +const sha256Handle = async ( + handle: FileHandle, + signal?: AbortSignal, +): Promise => { const hash = createHash("sha256"); const chunk = Buffer.allocUnsafe(64 * 1024); let position = 0; while (true) { + throwIfTargetResolutionCancelled(signal); const observed = await handle.read(chunk, 0, chunk.length, position); + throwIfTargetResolutionCancelled(signal); if (observed.bytesRead === 0) break; hash.update(chunk.subarray(0, observed.bytesRead)); position += observed.bytesRead; @@ -233,19 +272,23 @@ const resolveAppBundle = async ( const readExecutableMetadata = async ( handle: FileHandle, hostArchitecture: NodeJS.Architecture, + signal?: AbortSignal, ): Promise> => { + throwIfTargetResolutionCancelled(signal); const prefix = Buffer.alloc(4096); const prefixRead = await handle.read(prefix, 0, prefix.length, 0); + throwIfTargetResolutionCancelled(signal); const bytes = prefix.subarray(0, prefixRead.bytesRead); // Header commitments such as Mach-O load commands and FAT slices are // checked against the whole file, not the probed prefix. const fileSize = (await handle.stat()).size; + throwIfTargetResolutionCancelled(signal); if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) { const offset = mzWindowsHeaderOffset(bytes); if (offset !== null) { if (offset < 64) return err("invalid Windows new-header offset in MZ image"); - return readPeMetadata(handle, offset); + return readPeMetadata(handle, offset, signal); } // MZ relocation records may extend past the initial probe; their format // bounds are at most 65535 records inside a 65535-paragraph header. @@ -261,6 +304,7 @@ const readExecutableMetadata = async ( ) { const table = Buffer.alloc(tableEnd); const observed = await handle.read(table, 0, table.length, 0); + throwIfTargetResolutionCancelled(signal); return parseExecutableHeader( table.subarray(0, observed.bytesRead), hostArchitecture, @@ -278,6 +322,7 @@ const readExecutableMetadata = async ( if (count <= 128 && required > bytes.length) { const header = Buffer.alloc(required); const headerRead = await handle.read(header, 0, header.length, 0); + throwIfTargetResolutionCancelled(signal); return parseExecutableHeader( header.subarray(0, headerRead.bytesRead), hostArchitecture, @@ -292,7 +337,9 @@ const readExecutableMetadata = async ( const readPeMetadata = async ( handle: FileHandle, offset: number, + signal?: AbortSignal, ): Promise> => { + throwIfTargetResolutionCancelled(signal); const fileHeader = Buffer.alloc(24); const fileHeaderRead = await handle.read( fileHeader, @@ -300,6 +347,7 @@ const readPeMetadata = async ( fileHeader.length, offset, ); + throwIfTargetResolutionCancelled(signal); if (fileHeaderRead.bytesRead !== fileHeader.length) return err("invalid or truncated PE header"); const signature = fileHeader.toString("ascii", 0, 2); @@ -309,6 +357,7 @@ const readPeMetadata = async ( if (optionalHeaderSize > 4096) return err("invalid PE optional header size"); const record = Buffer.alloc(24 + optionalHeaderSize); const recordRead = await handle.read(record, 0, record.length, offset); + throwIfTargetResolutionCancelled(signal); return recordRead.bytesRead === record.length ? parsePeRecord(record) : err("invalid or truncated PE header"); diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index f23cee936..b51c88656 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -201,6 +201,7 @@ const runAnalysis = async ( const prepared = await prepareSnapshot({ path, snapshotPath, + signal, ...(options.formatHint === undefined ? {} : { formatHint: options.formatHint }), @@ -434,6 +435,7 @@ const prepareSnapshot = async (options: { readonly path: string; readonly formatHint?: ExecutableFormatHint; readonly snapshotPath: string | undefined; + readonly signal: AbortSignal; }): Promise< Result< { readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget }, @@ -445,13 +447,12 @@ const prepareSnapshot = async (options: { return ok({}); const loaded = await readAnalysisSnapshot(snapshotPath); if (!loaded.ok) return loaded; - const target = await parseBinaryTarget( - path, - process.cwd(), - process.arch, - undefined, - options.formatHint, - ); + const target = await parseBinaryTarget(path, { + signal: options.signal, + ...(options.formatHint === undefined + ? {} + : { formatHint: options.formatHint }), + }); if (!target.ok) return target; if (!snapshotMatchesTarget(loaded.value.target, target.value)) return err( diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index 95ecfbfd2..5426a6453 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -4,6 +4,7 @@ import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js"; import { join } from "node:path"; import { analysisErrorRemediationAction } from "../domain/analysisErrorPresentation.js"; +import { BinaryTargetError } from "../domain/configurationErrors.js"; import { parseBinaryTarget } from "./BinaryTargetResolver.js"; import { execFileOutput } from "../process/ExecFileOutput.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -324,10 +325,18 @@ export const systemDoctorHost = ( readMacosVersion(hostExecFileOutput, commandEnvironment), linuxDistribution: readLinuxDistribution, async validTarget(path) { - return (await parseBinaryTarget(path, process.cwd(), architecture)).ok; + return ( + await parseBinaryTarget(path, { + cwd: process.cwd(), + hostArchitecture: architecture, + }) + ).ok; }, async inspectTarget(path) { - const result = await parseBinaryTarget(path, process.cwd(), architecture); + const result = await parseBinaryTarget(path, { + cwd: process.cwd(), + hostArchitecture: architecture, + }); if (result.ok) return { name: "target", @@ -336,19 +345,21 @@ export const systemDoctorHost = ( detail: path, }; const error = result.error; + const targetError = + error instanceof BinaryTargetError ? error : undefined; return { name: "target", ok: false, classification: - error.constraint === "directory_requires_file" + targetError?.constraint === "directory_requires_file" ? "unsupported_target" : "config_drift", detail: path, details: { - reason: error.reason, - ...(error.constraint === undefined + reason: targetError?.reason ?? error.message, + ...(targetError?.constraint === undefined ? {} - : { constraint: error.constraint }), + : { constraint: targetError.constraint }), }, remediation: analysisErrorRemediationAction(error), }; diff --git a/src/application/android/AndroidAnalysisService.ts b/src/application/android/AndroidAnalysisService.ts index fe8c8f650..a126df57c 100644 --- a/src/application/android/AndroidAnalysisService.ts +++ b/src/application/android/AndroidAnalysisService.ts @@ -29,7 +29,9 @@ export class AndroidAnalysisService { const request = androidRequestSchema.safeParse({ operation, input }); if (!request.success) return err(new AnalysisInputError(operation, { cause: request.error })); - const target = await parseBinaryTarget(request.data.input.path); + const target = await parseBinaryTarget(request.data.input.path, { + ...(options?.signal === undefined ? {} : { signal: options.signal }), + }); if (!target.ok) return target; const executed = await this.provider.execute( target.value, diff --git a/src/application/binary/BinarySessionOpen.ts b/src/application/binary/BinarySessionOpen.ts index cde06c29d..1a7f635bc 100644 --- a/src/application/binary/BinarySessionOpen.ts +++ b/src/application/binary/BinarySessionOpen.ts @@ -65,13 +65,15 @@ export const resolveSessionOpen = async ( input: ResolveSessionOpenInput, ): Promise> => { const { path, options } = input; - const parsed = await parseBinaryTarget( - path, - process.cwd(), - process.arch, - options.targetKind, - options.formatHint, - ); + const parsed = await parseBinaryTarget(path, { + ...(options.targetKind === undefined + ? {} + : { targetKind: options.targetKind }), + ...(options.formatHint === undefined + ? {} + : { formatHint: options.formatHint }), + ...(options.signal === undefined ? {} : { signal: options.signal }), + }); if (!parsed.ok) return parsed; return resolveSessionTarget({ ...input, target: parsed.value }); }; diff --git a/tests/boundary/filesystem/binaryTarget.test.ts b/tests/boundary/filesystem/binaryTarget.test.ts index 6505c42f2..69ff26fab 100644 --- a/tests/boundary/filesystem/binaryTarget.test.ts +++ b/tests/boundary/filesystem/binaryTarget.test.ts @@ -226,12 +226,16 @@ describe("binary target I/O: filesystem and app bundle target resolution", () => const directory = await createTestTempDirectory("rea-target-"); await writeFile(join(directory, "sample.hop"), "database"); await writeFile(join(directory, "text"), "hello"); - const database = await parseBinaryTarget("sample.hop", directory); + const database = await parseBinaryTarget("sample.hop", { cwd: directory }); expect(database.ok && database.value.sha256).toBe( "3549b0028b75d981cdda2e573e9cb49dedc200185876df299f912b79f69dabd8", ); - expect((await parseBinaryTarget("text", directory)).ok).toBe(false); - expect((await parseBinaryTarget("missing", directory)).ok).toBe(false); + expect((await parseBinaryTarget("text", { cwd: directory })).ok).toBe( + false, + ); + expect((await parseBinaryTarget("missing", { cwd: directory })).ok).toBe( + false, + ); }); it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( @@ -242,7 +246,10 @@ describe("binary target I/O: filesystem and app bundle target resolution", () => await writeFile(path, thinMach(0xcffaedfe, 0x0100000c)); await chmod(path, 0); try { - const result = await parseBinaryTarget(path, directory, "arm64"); + const result = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok).toBe(false); if (result.ok) return; expect(result.error).toMatchObject({ path, systemCode: "EACCES" }); @@ -275,7 +282,10 @@ describe("binary target I/O: filesystem and app bundle target resolution", () => join(programs, "Example & Tool"), thinMach(0xfeedfacf, 0x0100000c), ); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(join(programs, "Example & Tool")), format: "mach-o", @@ -300,7 +310,14 @@ describe("binary target I/O: filesystem and app bundle target resolution", () => await mkdir(join(contents, "MacOS"), { recursive: true }); if (plist !== undefined) await writeFile(join(contents, "Info.plist"), plist); - expect((await parseBinaryTarget(app, directory, "arm64")).ok).toBe(false); + expect( + ( + await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }) + ).ok, + ).toBe(false); }); it.skipIf(process.platform === "win32")( @@ -318,7 +335,14 @@ describe("binary target I/O: filesystem and app bundle target resolution", () => "CFBundleExecutableEscaping", ); await symlink(outside, join(programs, "Escaping")); - expect((await parseBinaryTarget(app, directory, "arm64")).ok).toBe(false); + expect( + ( + await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }) + ).ok, + ).toBe(false); }, ); }); @@ -327,12 +351,11 @@ describe("binary target I/O: explicit kinds and executable headers", () => { it("honors an explicit database kind without relying on the file suffix", async () => { const directory = await createTestTempDirectory("rea-target-"); await writeFile(join(directory, "saved-analysis"), "database"); - const result = await parseBinaryTarget( - "saved-analysis", - directory, - "arm64", - "database", - ); + const result = await parseBinaryTarget("saved-analysis", { + cwd: directory, + hostArchitecture: "arm64", + targetKind: "database", + }); expect(result.ok && result.value).toMatchObject({ kind: "database", format: "analysis-database", @@ -343,7 +366,10 @@ describe("binary target I/O: explicit kinds and executable headers", () => { const directory = await createTestTempDirectory("rea-target-"); const path = join(directory, "delayed.exe"); await writeFile(path, pe(0x8664, 8192)); - const result = await parseBinaryTarget(path, directory, "x64"); + const result = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "x64", + }); expect(result.ok && result.value).toMatchObject({ format: "pe", architecture: "x86_64", @@ -354,7 +380,10 @@ describe("binary target I/O: explicit kinds and executable headers", () => { const directory = await createTestTempDirectory("rea-target-"); const path = join(directory, "truncated"); await writeFile(path, thinMach(0xcffaedfe, 0x0100000c).subarray(0, 12)); - const result = await parseBinaryTarget(path, directory, "arm64"); + const result = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok).toBe(false); expect(result.ok ? undefined : result.error).toMatchObject({ path, @@ -369,7 +398,10 @@ describe("binary target I/O: explicit kinds and executable headers", () => { const header = thinMach(0xcffaedfe, 0x0100000c); header.writeUInt32LE(8192, 20); await writeFile(path, Buffer.concat([header, Buffer.alloc(8192)])); - const result = await parseBinaryTarget(path, directory, "arm64"); + const result = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ format: "mach-o", architecture: "arm64", @@ -391,7 +423,10 @@ describe("app executable filename fidelity", () => { `CFBundleExecutable${name}`, ); await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c)); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(executable), format: "mach-o", @@ -416,7 +451,10 @@ describe("app executable filename fidelity", () => { `CFBundleExecutable${encoded}`, ); await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c)); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(executable), format: "mach-o", @@ -449,7 +487,10 @@ describe("app executable filename fidelity", () => { join(contents, "MacOS", "Inner"), thinMach(0xfeedfacf, 0x0100000c), ); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(executable), }); @@ -469,7 +510,10 @@ describe("app executable filename fidelity", () => { `${entry}CFBundleExecutableApp`, ); await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c)); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(executable), }); @@ -495,7 +539,10 @@ describe("app executable filename fidelity", () => { plist, ]); await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c)); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(executable), format: "mach-o", @@ -515,7 +562,10 @@ describe("iOS-style app bundle targets", () => { await mkdir(app); await writeFile(join(app, "Info.plist"), plist("Flat")); await writeFile(join(app, "Flat"), thinMach(0xfeedfacf, 0x0100000c)); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(join(app, "Flat")), bundleInfoPlist: join(await realpath(app), "Info.plist"), @@ -535,7 +585,10 @@ describe("iOS-style app bundle targets", () => { thinMach(0xfeedfacf, 0x0100000c), ); await symlink("bin/real", join(app, "Linked")); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(join(app, "bin", "real")), bundleInfoPlist: join(await realpath(app), "Info.plist"), @@ -556,7 +609,10 @@ describe("iOS-style app bundle targets", () => { join(contents, "MacOS", "Linked"), thinMach(0xfeedfacf, 0x0100000c), ); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(join(contents, "MacOS", "Linked")), }); @@ -572,7 +628,10 @@ describe("iOS-style app bundle targets", () => { await mkdir(join(wrapper, "Locked.app"), { recursive: true }); await chmod(wrapper, 0o000); try { - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); if (result.ok) throw new Error("Expected a permission denial"); expect(result.error.message).toContain("permission denied"); } finally { @@ -591,14 +650,24 @@ describe("iOS-style app bundle targets", () => { await writeFile(join(wrapped, "Info.plist"), plist("Phone")); await writeFile(join(wrapped, "Phone"), thinMach(0xfeedfacf, 0x0100000c)); await symlink("Wrapper/Phone.app", join(app, "WrappedBundle")); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); expect(result.ok && result.value).toMatchObject({ path: await realpath(join(wrapped, "Phone")), format: "mach-o", }); await mkdir(join(app, "Wrapper", "Second.app")); - expect((await parseBinaryTarget(app, directory, "arm64")).ok).toBe(false); + expect( + ( + await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }) + ).ok, + ).toBe(false); }, ); @@ -612,7 +681,10 @@ describe("iOS-style app bundle targets", () => { await writeFile(outside, thinMach(0xfeedfacf, 0x0100000c)); await writeFile(join(app, "Info.plist"), plist("Escaping")); await symlink(outside, join(app, "Escaping")); - const result = await parseBinaryTarget(app, directory, "arm64"); + const result = await parseBinaryTarget(app, { + cwd: directory, + hostArchitecture: "arm64", + }); if (result.ok) throw new Error("Expected an escaping program file"); expect(result.error.message).toContain("leaves the bundle root"); }, diff --git a/tests/boundary/filesystem/dosComTarget.test.ts b/tests/boundary/filesystem/dosComTarget.test.ts index ce5738b3d..7bd3eae7b 100644 --- a/tests/boundary/filesystem/dosComTarget.test.ts +++ b/tests/boundary/filesystem/dosComTarget.test.ts @@ -11,13 +11,11 @@ describe("DOS COM admission", () => { const path = join(directory, "fixture.js"); const bytes = Buffer.from("b83412c3", "hex"); await writeFile(path, bytes); - const target = await parseBinaryTarget( - path, - directory, - "arm64", - undefined, - "dos-com", - ); + const target = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "arm64", + formatHint: "dos-com", + }); expect(target).toMatchObject({ ok: true, value: { @@ -38,7 +36,11 @@ describe("DOS COM admission", () => { const path = join(directory, "fixture.com"); await writeFile(path, Buffer.alloc(length)); expect( - await parseBinaryTarget(path, directory, "x64", undefined, "dos-com"), + await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "x64", + formatHint: "dos-com", + }), ).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } }); }); it("rejects contradictory target kind", async () => { @@ -46,7 +48,12 @@ describe("DOS COM admission", () => { const path = join(directory, "fixture.com"); await writeFile(path, Buffer.from("c3", "hex")); expect( - await parseBinaryTarget(path, directory, "x64", "database", "dos-com"), + await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "x64", + targetKind: "database", + formatHint: "dos-com", + }), ).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } }); }); }); diff --git a/tests/boundary/process/jadxIntegration.test.ts b/tests/boundary/process/jadxIntegration.test.ts index 6c90e1728..5d79199bb 100644 --- a/tests/boundary/process/jadxIntegration.test.ts +++ b/tests/boundary/process/jadxIntegration.test.ts @@ -1,5 +1,5 @@ import { expect, it as test, vi } from "vitest"; -import { access, readFile, writeFile } from "node:fs/promises"; +import { access, readFile, truncate, writeFile } from "node:fs/promises"; import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js"; import { AndroidAnalysisService } from "../../../src/application/android/AndroidAnalysisService.js"; import { JadxProvider } from "../../../src/android/JadxProvider.js"; @@ -17,6 +17,30 @@ import { writeJadxJarInventory } from "../../fixtures/android/jadxJar.js"; const it = test.skipIf(process.platform === "win32"); +it("cancels Android admission while hashing the selected APK", async () => { + const { service, apk, launches, provider } = await setup(); + await writeFile(apk, Buffer.from([0x50, 0x4b, 0x03, 0x04])); + await truncate(apk, 1024 * 1024 * 1024); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 100); + try { + const result = await service.execute( + "inspect_android_package", + { path: apk }, + { signal: controller.signal }, + ); + expect(result).toMatchObject({ + ok: false, + error: { _tag: "AnalysisCancelledError" }, + }); + expect(launches).toHaveLength(0); + } finally { + clearTimeout(timer); + await provider.close(); + await verifyCleanup(launches); + } +}); + it("rejects a copied JAR that differs from its admitted session identity", async () => { const { jar } = await setup(); const admitted = await hashAndroidFile(jar); From 25711ad2590af136dfb301839dddd6d30971ba76 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:16:28 +0800 Subject: [PATCH 012/189] test: exercise source test selection through Git and Vitest --- .../filesystem/developmentTests.test.ts | 110 ++++++++++++++++++ tests/evaluation/developmentTestPlan.test.ts | 87 -------------- 2 files changed, 110 insertions(+), 87 deletions(-) create mode 100644 tests/boundary/filesystem/developmentTests.test.ts delete mode 100644 tests/evaluation/developmentTestPlan.test.ts diff --git a/tests/boundary/filesystem/developmentTests.test.ts b/tests/boundary/filesystem/developmentTests.test.ts new file mode 100644 index 000000000..1b52bb475 --- /dev/null +++ b/tests/boundary/filesystem/developmentTests.test.ts @@ -0,0 +1,110 @@ +import { + copyFile, + mkdir, + readFile, + symlink, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; + +import { expect, it } from "vitest"; + +import { execFileOutput } from "../../../src/process/ExecFileOutput.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const run = (root: string, command: string, arguments_: readonly string[]) => + execFileOutput(command, arguments_, { + cwd: root, + stopSignal: "SIGTERM", + timeout: 20_000, + }); + +const commit = (root: string, message: string) => + run(root, "git", [ + "-c", + "user.name=REA fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgSign=false", + "commit", + "--quiet", + "-m", + message, + ]); + +const fixture = async () => { + const root = await createTestTempDirectory("rea-development-tests-"); + await mkdir(join(root, "scripts", "lib"), { recursive: true }); + await mkdir(join(root, "src")); + for (const path of [ + "scripts/run-development-tests.mjs", + "scripts/lib/development-tests.mjs", + ]) + await copyFile(join(process.cwd(), path), join(root, path)); + await symlink( + join(process.cwd(), "node_modules"), + join(root, "node_modules"), + process.platform === "win32" ? "junction" : undefined, + ); + await writeFile(join(root, "package.json"), '{"type":"module"}\n'); + await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n"); + await writeFile( + join(root, "vitest.config.mjs"), + 'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n', + ); + await writeFile(join(root, "src", "value.ts"), "export const value = 1;\n"); + await writeFile( + join(root, "src", "value.test.ts"), + 'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n', + ); + await run(root, "git", ["init", "--quiet"]); + await run(root, "git", ["add", "."]); + await commit(root, "fixture"); + return root; +}; + +const testCommand = (root: string, ...arguments_: string[]) => + run(root, process.execPath, [ + "scripts/run-development-tests.mjs", + ...arguments_, + ]); + +it("executes an explicitly selected source test on a clean tree without build artifacts", async () => { + const root = await fixture(); + const { stdout: status } = await run(root, "git", ["status", "--porcelain"]); + expect(status).toBe(""); + await testCommand(root, "local", "src/value.test.ts"); + expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1"); +}); + +it("uses committed dependency changes since the requested Git base to select source tests", async () => { + const root = await fixture(); + const { stdout: base } = await run(root, "git", ["rev-parse", "HEAD"]); + await writeFile(join(root, "src", "value.ts"), "export const value = 2;\n"); + await run(root, "git", ["add", "src/value.ts"]); + await commit(root, "change dependency"); + await expect( + testCommand(root, "changed", "--base", base.trim()), + ).rejects.toMatchObject({ + code: 1, + stdout: expect.stringContaining("src/value.test.ts"), + stderr: expect.stringContaining("expected 2 to be 1"), + }); +}); + +it("rejects a compiled boundary in the source-only command and a missing exact test", async () => { + const root = await fixture(); + await expect( + testCommand(root, "local", "tests/acceptance/runtime.test.ts"), + ).rejects.toMatchObject({ + code: 1, + stderr: expect.stringContaining("Use test:focused"), + }); + await expect( + testCommand(root, "local", "src/missing.test.ts"), + ).rejects.toMatchObject({ + code: 1, + stderr: expect.stringContaining("ENOENT"), + }); +}); diff --git a/tests/evaluation/developmentTestPlan.test.ts b/tests/evaluation/developmentTestPlan.test.ts deleted file mode 100644 index 0544aa1f4..000000000 --- a/tests/evaluation/developmentTestPlan.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - developmentTestPlan, - parseDevelopmentTestRequest, -} from "../../scripts/lib/development-tests.mjs"; - -describe("development test selection", () => { - it("keeps dirty source feedback independent of compiled artifacts", () => { - const plan = developmentTestPlan(parseDevelopmentTestRequest("local", [])); - expect(plan.needsBuild).toBe(false); - expect(plan.vitestArguments).toContain("--changed"); - expect(plan.vitestArguments).not.toContain("acceptance"); - expect(plan.vitestArguments).not.toContain("process-global"); - }); - - it("always runs explicitly selected source tests, including on a clean tree", () => { - const path = "src/config.test.ts"; - const plan = developmentTestPlan( - parseDevelopmentTestRequest("local", [path, path]), - ); - expect(plan.needsBuild).toBe(false); - expect( - plan.vitestArguments.filter((argument) => argument === path), - ).toHaveLength(1); - expect( - plan.vitestArguments.some((argument) => argument.startsWith("--changed")), - ).toBe(false); - expect(plan.vitestArguments).not.toContain("--passWithNoTests"); - }); - - it("builds before explicitly selected compiled boundaries", () => { - const plan = developmentTestPlan( - parseDevelopmentTestRequest("focused", [ - "src/config.test.ts", - "tests/acceptance/applications/runtime.test.ts", - ]), - ); - expect(plan.needsBuild).toBe(true); - expect(plan.vitestArguments).not.toContain("--changed"); - }); - - it("prepares test catalogs and managed evidence only for their consumers", () => { - const ordinary = developmentTestPlan( - parseDevelopmentTestRequest("focused", [ - "tests/boundary/mcp/sessionMcp.test.ts", - ]), - ); - expect(ordinary.artifactTasks).toEqual([]); - const consumers = developmentTestPlan( - parseDevelopmentTestRequest("focused", [ - "tests/boundary/mcp/toolSchemaValidity.test.ts", - "tests/boundary/filesystem/setupSkill.test.ts", - ]), - ); - expect(consumers.artifactTasks).toEqual([ - "artifacts:mcp-catalog", - "artifacts:managed-evidence", - ]); - }); - - it("uses the resolved branch merge base for committed source changes", () => { - const request = parseDevelopmentTestRequest("changed", ["--base", "main"]); - const plan = developmentTestPlan(request, "a".repeat(40)); - expect(request.base).toBe("main"); - expect(plan.vitestArguments).toContain(`--changed=${"a".repeat(40)}`); - expect(() => developmentTestPlan(request)).toThrow( - "resolved Git merge base", - ); - }); - - it.each([ - ["focused", []], - ["focused", ["../src/config.test.ts"]], - ["focused", ["src/../config.test.ts"]], - ["focused", ["--passWithNoTests"]], - ["focused", ["--changed"]], - ["local", ["tests/acceptance/applications/runtime.test.ts"]], - ["changed", ["--base"]], - ["changed", ["--base=--help"]], - ["changed", ["src/config.test.ts"]], - ["local", ["--base", "main"]], - ["unknown", []], - ])("rejects invalid %s selections: %j", (mode, paths) => { - expect(() => parseDevelopmentTestRequest(mode, paths)).toThrow(); - }); -}); From e64678e8f9768dd819d8f5f12cc844a6660ff2c5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:16:44 +0800 Subject: [PATCH 013/189] fix(mcp): retry failed shutdown resources and retain failure reasons --- src/main/shutdown.ts | 117 ++++++++++++++++++++-------- tests/boundary/mcp/shutdown.test.ts | 91 ++++++++++++++++++++++ 2 files changed, 177 insertions(+), 31 deletions(-) diff --git a/src/main/shutdown.ts b/src/main/shutdown.ts index fac2571ab..f6722eb97 100644 --- a/src/main/shutdown.ts +++ b/src/main/shutdown.ts @@ -8,6 +8,11 @@ import type { JsonValue } from "../domain/jsonValue.js"; import type { RuntimeDependencies } from "./types.js"; import { MCP_SHUTDOWN_FAILED } from "./messages.js"; +interface ShutdownCleanupOwner { + readonly close: () => Promise; + closed: boolean; +} + export const createShutdown = (input: { readonly handle: StdioServerHandle; readonly closeAndroid?: () => Promise; @@ -19,22 +24,51 @@ export const createShutdown = (input: { readonly request: () => void; } => { const { handle, session, dependencies, serverLogger } = input; - let shutdownPromise: Promise | undefined; + let shutdownAttempt: Promise | undefined; + const cleanupOwners: ShutdownCleanupOwner[] = [ + { close: () => handle.close(), closed: false }, + ...(input.closeAndroid === undefined + ? [] + : [{ close: input.closeAndroid, closed: false }]), + { + close: async () => { + const closed = await session.close({ retainProviderDocuments: true }); + if (!closed.ok) throw closed.error; + }, + closed: false, + }, + ]; + let shutdownUnregistered = false; let unregisterShutdown = (): void => undefined; const shutdown = async (): Promise => { - shutdownPromise ??= (async () => { - unregisterShutdown(); - const results = await Promise.allSettled([ - handle.close(), - input.closeAndroid?.(), - session.close({ retainProviderDocuments: true }).then((closed) => { - if (!closed.ok) throw closed.error; + if (shutdownAttempt !== undefined) return shutdownAttempt; + const pending = cleanupOwners.filter(({ closed }) => !closed); + const attempt = (async () => { + const results = await Promise.allSettled( + pending.map(async (owner) => { + await owner.close(); + owner.closed = true; }), - ]); + ); + const failures: unknown[] = []; for (const result of results) - if (result.status === "rejected") throw result.reason; + if (result.status === "rejected") failures.push(result.reason); + if (failures.length === 1) throw failures[0]; + if (failures.length > 1) + throw new AggregateError( + failures, + "Multiple MCP cleanup operations failed", + ); + if (!shutdownUnregistered) { + unregisterShutdown(); + shutdownUnregistered = true; + } })(); - return shutdownPromise; + shutdownAttempt = attempt; + void attempt.catch(() => { + if (shutdownAttempt === attempt) shutdownAttempt = undefined; + }); + return attempt; }; const requestShutdown = (): void => { shutdown().catch((cause: unknown) => { @@ -55,26 +89,47 @@ export const createShutdown = (input: { const describeShutdownFailure = ( cause: unknown, +): Readonly> => + describeShutdownFailureNode(cause, new WeakSet()); + +const describeShutdownFailureNode = ( + cause: unknown, + active: WeakSet, ): Readonly> => { - if (cause instanceof AnalysisError) - return { analysis_error: projectAnalysisError(cause) }; - if (cause instanceof Error) { - const code = "code" in cause ? cause.code : undefined; - return { - name: cause.name, - message: cause.message, - ...(typeof code === "string" || - (typeof code === "number" && Number.isFinite(code)) - ? { code } - : {}), - }; + if (typeof cause === "object" && cause !== null) { + if (active.has(cause)) return { type: "cyclic_error" }; + active.add(cause); + } + try { + if (cause instanceof AnalysisError) + return { analysis_error: projectAnalysisError(cause) }; + if (cause instanceof Error) { + const code = "code" in cause ? cause.code : undefined; + return { + name: cause.name, + message: cause.message, + ...(typeof code === "string" || + (typeof code === "number" && Number.isFinite(code)) + ? { code } + : {}), + ...(cause instanceof AggregateError + ? { + errors: cause.errors.map((error: unknown) => + describeShutdownFailureNode(error, active), + ), + } + : {}), + }; + } + if ( + cause === null || + typeof cause === "string" || + typeof cause === "boolean" || + (typeof cause === "number" && Number.isFinite(cause)) + ) + return { type: cause === null ? "null" : typeof cause, value: cause }; + return { type: typeof cause }; + } finally { + if (typeof cause === "object" && cause !== null) active.delete(cause); } - if ( - cause === null || - typeof cause === "string" || - typeof cause === "boolean" || - (typeof cause === "number" && Number.isFinite(cause)) - ) - return { type: cause === null ? "null" : typeof cause, value: cause }; - return { type: typeof cause }; }; diff --git a/tests/boundary/mcp/shutdown.test.ts b/tests/boundary/mcp/shutdown.test.ts index c939fbbc7..f1720bb62 100644 --- a/tests/boundary/mcp/shutdown.test.ts +++ b/tests/boundary/mcp/shutdown.test.ts @@ -116,5 +116,96 @@ it("reports a typed binary cleanup failure and retains the client for retry", as ]); expect(retainDocument).toBe(true); cleanupAllowed = true; + requests[0]?.(); + await new Promise((resolve) => setImmediate(resolve)); expect((await session.close()).ok).toBe(true); }); + +it("retries only failed cleanup owners after concurrent shutdown requests", async () => { + const requests: Array<() => void> = []; + const logs: string[] = []; + const exitCodes: number[] = []; + let unregisterCount = 0; + let handleCalls = 0; + let androidCalls = 0; + let sessionCalls = 0; + const dependencies: RuntimeDependencies = { + env: {}, + serve: () => { + throw new Error("unused fixture transport"); + }, + writeStderr: () => undefined, + setExitCode: (code) => exitCodes.push(code), + registerShutdown: (request) => { + requests.push(request); + return () => { + unregisterCount += 1; + }; + }, + }; + const session = createTestBinarySession(() => ({ + execute: async () => observed(null), + close: async () => { + sessionCalls += 1; + return ok(null); + }, + })); + const [target] = await createBinarySessionTargets(); + if (target === undefined) throw new Error("Missing fixture target"); + expect((await session.open(target)).ok).toBe(true); + const lifecycle = createShutdown({ + handle: { + close: async () => { + handleCalls += 1; + if (handleCalls === 1) throw new Error("first handle close failed"); + }, + }, + closeAndroid: async () => { + androidCalls += 1; + if (androidCalls === 1) throw new Error("first Android close failed"); + }, + session, + dependencies, + serverLogger: pino( + { level: "debug" }, + { write: (line) => logs.push(line) }, + ), + }); + + const first = lifecycle.shutdown(); + const concurrent = lifecycle.shutdown(); + requests[0]?.(); + await expect(first).rejects.toBeInstanceOf(AggregateError); + await expect(concurrent).rejects.toBeInstanceOf(AggregateError); + await expect(first).rejects.toMatchObject({ + errors: [ + { message: "first handle close failed" }, + { message: "first Android close failed" }, + ], + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(exitCodes).toEqual([1]); + expect(logs.map((line) => JSON.parse(line))).toContainEqual( + expect.objectContaining({ + msg: "MCP shutdown rejected", + failure_cause: expect.objectContaining({ + errors: [ + expect.objectContaining({ message: "first handle close failed" }), + expect.objectContaining({ message: "first Android close failed" }), + ], + }), + }), + ); + expect([handleCalls, androidCalls, sessionCalls, unregisterCount]).toEqual([ + 1, 1, 1, 0, + ]); + + await lifecycle.shutdown(); + expect([handleCalls, androidCalls, sessionCalls, unregisterCount]).toEqual([ + 2, 2, 1, 1, + ]); + await lifecycle.shutdown(); + expect([handleCalls, androidCalls, sessionCalls, unregisterCount]).toEqual([ + 2, 2, 1, 1, + ]); +}); From e11f4d371abaa8cb65ebf7b94fa216329fd78d88 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:19:23 +0800 Subject: [PATCH 014/189] fix(mcp): admit composed analysis through result bookkeeping --- src/application/binary/BinarySession.ts | 27 +++ src/application/binary/BinarySessionPort.ts | 6 + src/main/transport.ts | 17 +- src/server/analysisAdmission.ts | 29 +++ src/server/createServer.ts | 51 ++--- src/server/registerArtifactTools.ts | 5 +- src/server/registerCloseLifecycleTool.ts | 16 +- src/server/registerEnhancedTools.ts | 180 +++++++++--------- src/server/registerEvidenceTools.ts | 140 ++++++++------ src/server/registerManagedTools.ts | 20 +- src/server/registerNativeTools.ts | 10 +- src/server/registerOfficialTools.ts | 85 +++++---- src/server/registerSessionTools.ts | 28 ++- tests/acceptance/nonBinaryComposition.test.ts | 13 +- tests/acceptance/webModuleCli.test.ts | 9 +- .../mcp/advertisedPatternsVMode.test.ts | 2 +- tests/boundary/mcp/analysisViewMcp.test.ts | 3 +- .../mcp/artifactMcp.inlineInventory.test.ts | 4 +- tests/boundary/mcp/artifactMcp.test.ts | 14 +- .../boundary/mcp/binaryDiagnosticsMcp.test.ts | 5 +- tests/boundary/mcp/browserMcp.test.ts | 17 +- tests/boundary/mcp/browserScenarioMcp.test.ts | 19 +- .../boundary/mcp/bundleComparisonMcp.test.ts | 2 +- tests/boundary/mcp/clientCapabilities.test.ts | 4 +- .../mcp/comparisonUnknownsMcp.test.ts | 2 +- tests/boundary/mcp/dylibResolutionMcp.test.ts | 2 +- tests/boundary/mcp/electronMcp.test.ts | 49 +++-- ....01-lists-the-complete-target-open.test.ts | 2 +- tests/boundary/mcp/enhancedToolsHarness.ts | 2 +- .../boundary/mcp/evidenceBundleInline.test.ts | 2 +- .../mcp/evidenceExportCancellation.test.ts | 2 +- tests/boundary/mcp/evmInterfaceMcp.test.ts | 5 +- tests/boundary/mcp/firmwareMcp.test.ts | 9 +- .../mcp/functionComparisonMcp.test.ts | 8 +- tests/boundary/mcp/ghidraMcpHarness.ts | 5 +- .../mcp/investigationAnalysisMcp.test.ts | 2 +- .../javascriptAnalysisCancellation.test.ts | 2 +- .../mcp/javascriptRecoveryMcp.test.ts | 9 +- .../javascriptRuntimeObservationMcp.test.ts | 17 +- .../mcp/keyedArchiveNumberMetadataMcp.test.ts | 4 +- tests/boundary/mcp/largeToolResult.test.ts | 28 +-- tests/boundary/mcp/managedMcp.test.ts | 29 +-- .../mcp/mobileApplicationGraphMcp.test.ts | 2 +- .../mcp/nativeCallObservationMcp.test.ts | 4 +- tests/boundary/mcp/nativeDemangleMcp.test.ts | 4 +- .../boundary/mcp/nativeInputContracts.test.ts | 2 +- .../nativeSignatureTargetBindingMcp.test.ts | 2 +- tests/boundary/mcp/officialArguments.test.ts | 2 +- tests/boundary/mcp/officialTools.test.ts | 2 +- .../mcp/optionalProviderIsolation.test.ts | 8 +- .../processComparisonDiagnosticsMcp.test.ts | 2 +- .../mcp/processEvidenceIdentityMcp.test.ts | 2 +- .../mcp/processTraceAdaptersParity.test.ts | 5 +- tests/boundary/mcp/progressMcp.test.ts | 4 +- tests/boundary/mcp/promptMcp.test.ts | 12 +- .../boundary/mcp/providerSelectionMcp.test.ts | 5 +- .../mcp/reconstructionCoverageMcp.test.ts | 2 +- .../reconstructionObligationLedgerMcp.test.ts | 2 +- tests/boundary/mcp/recordedCrashMcp.test.ts | 5 +- .../retainedApplicationEvidenceMcp.test.ts | 2 +- tests/boundary/mcp/serverIdentity.test.ts | 4 +- tests/boundary/mcp/serverLifecycleMcp.test.ts | 2 +- tests/boundary/mcp/serverUnknownsMcp.test.ts | 38 ++-- tests/boundary/mcp/serverWorkflowMcp.test.ts | 7 +- tests/boundary/mcp/sessionMcp.test.ts | 16 +- tests/boundary/mcp/sessionMcpHarness.ts | 9 +- tests/boundary/mcp/webModuleTraceMcp.test.ts | 5 +- .../boundary/mcp/webNetworkCaptureMcp.test.ts | 5 +- tests/boundary/mcp/webRuntimeMcp.test.ts | 9 +- .../boundary/mcp/webSourceLocationMcp.test.ts | 5 +- .../mcp/workflowSnapshotReplayMcp.test.ts | 107 ++++++++++- .../process/androidAnalysisMcp.test.ts | 14 +- ...processCaptureCancellationAdapters.test.ts | 2 +- .../processFilesystemCoverageAdapters.test.ts | 2 +- .../process/processSessionMcp.test.ts | 9 +- .../process/processTruncationAdapters.test.ts | 2 +- .../analysis-sessions/binarySession.test.ts | 31 +++ tests/fixtures/applicationMcpHarness.ts | 2 +- tests/fixtures/contractPresentation.mjs | 2 +- .../mcpDeliveryEnvironment.test.ts | 22 ++- 80 files changed, 774 insertions(+), 471 deletions(-) create mode 100644 src/server/analysisAdmission.ts diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index aa54a8c04..b9ff6a23c 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -507,6 +507,33 @@ export class BinarySession return call.finally(() => this.#calls.delete(call)); } + /** Admit one composed request until its result and session bookkeeping settle. */ + withAdmittedAnalysis( + operationName: string, + signal: AbortSignal | undefined, + operation: (analysis: AnalysisOperationPort) => Promise, + ): Promise> { + const generation = this.#transitionGeneration; + const transition = this.#transition; + const call = (async (): Promise> => { + const admission = await this.#waitForTransition( + operationName, + signal, + transition, + ); + if (!admission.ok) return admission; + return ok( + await operation({ + execute: (name, arguments_, options) => + this.#execute(name, arguments_, options, Promise.resolve()), + }), + ); + })(); + // Register synchronously before a lifecycle transition can snapshot calls. + this.#calls.set(call, generation); + return call.finally(() => this.#calls.delete(call)); + } + async #execute( name: Parameters[0], arguments_: Readonly>, diff --git a/src/application/binary/BinarySessionPort.ts b/src/application/binary/BinarySessionPort.ts index fc98c1f16..166479a06 100644 --- a/src/application/binary/BinarySessionPort.ts +++ b/src/application/binary/BinarySessionPort.ts @@ -32,6 +32,12 @@ export interface SavedAnalysisSnapshot { /** Target lifecycle used by CLI and MCP without exposing a concrete provider. */ export interface BinarySessionPort extends AnalysisOperationPort, InvestigationRecordPort { + /** Hold the active target binding through a complete composed operation. */ + withAdmittedAnalysis( + operationName: string, + signal: AbortSignal | undefined, + operation: (analysis: AnalysisOperationPort) => Promise, + ): Promise>; open( path: string, options?: { diff --git a/src/main/transport.ts b/src/main/transport.ts index 729b5d6d1..f8d6014f3 100644 --- a/src/main/transport.ts +++ b/src/main/transport.ts @@ -71,13 +71,16 @@ export const startMcpTransport = async ( serverContext.environment, ); androidProviders.push(android); - return (dependencies.createServer ?? createServer)(session, session, { - logger: serverContext.logger, - environment: serverContext.environment, - delivery: serverContext.delivery, - ...optionalProviders, - androidAnalysis: android, - }); + return (dependencies.createServer ?? createServer)( + { kind: "session", session }, + { + logger: serverContext.logger, + environment: serverContext.environment, + delivery: serverContext.delivery, + ...optionalProviders, + androidAnalysis: android, + }, + ); }, { onerror: () => { diff --git a/src/server/analysisAdmission.ts b/src/server/analysisAdmission.ts new file mode 100644 index 000000000..93e79e2b1 --- /dev/null +++ b/src/server/analysisAdmission.ts @@ -0,0 +1,29 @@ +import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; +import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { err, ok, type Result } from "../domain/result.js"; + +/** Run a provider-backed tool while its target binding stays admitted. */ +export type WithAdmittedAnalysis = ( + operationName: string, + signal: AbortSignal | undefined, + operation: (analysis: AnalysisOperationPort) => Promise, +) => Promise>; + +/** Select exactly one owner for a server's analysis operation binding. */ +export type ServerAnalysisSource = + | { readonly kind: "session"; readonly session: BinarySessionPort } + | { readonly kind: "fixed"; readonly analysis: AnalysisOperationPort }; + +/** Run against the source's explicit owner, admitting session-scoped work. */ +export const withAdmittedAnalysis = ( + source: ServerAnalysisSource, +): WithAdmittedAnalysis => + source.kind === "session" + ? (operationName, signal, operation) => + source.session.withAdmittedAnalysis(operationName, signal, operation) + : async (operationName, signal, operation) => + signal?.aborted === true + ? err(new AnalysisCancelledError(operationName)) + : ok(await operation(source.analysis)); diff --git a/src/server/createServer.ts b/src/server/createServer.ts index b0d95ecbb..20fae3fd2 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -17,7 +17,6 @@ import { import { parseMcpResponseBudget } from "../config/mcpResponseBudget.js"; import { isAbsolute } from "node:path"; -import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; import type { BrowserObservationPort } from "../application/BrowserObservationPort.js"; import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js"; @@ -68,6 +67,11 @@ import { registerGuidedPrompts } from "./registerPrompts.js"; import { registerSessionTools } from "./registerSessionTools.js"; import type { AvailabilityPolicy } from "../application/CapabilityInventory.js"; import { sessionAvailabilityPolicy } from "./sessionAvailabilityPolicy.js"; +import { + withAdmittedAnalysis, + type ServerAnalysisSource, +} from "./analysisAdmission.js"; +import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; const TARGET_FREE_INSTRUCTIONS = "REA provides reverse-engineering tools for local artifacts, native binaries, managed code, browser pages, and runtimes. Use the tool that directly answers the question; discover targets or inspect inventory only when needed. Tool results include inline Evidence and report their coverage and limitations."; @@ -168,10 +172,11 @@ const createMcpServer = ( * fixed-target seam used by focused tests and embedders. */ export const createServer = ( - analysis: AnalysisOperationPort, - session?: BinarySessionPort, + source: ServerAnalysisSource, options: CreateServerOptions = {}, ): EvidenceMcpServer => { + const session = source.kind === "session" ? source.session : undefined; + const analysis = source.kind === "session" ? source.session : source.analysis; const environment = snapshotEnvironment(options.environment ?? process.env); const delivery = selectToolResultDelivery(environment, options.delivery); const selectedOptions = { ...options, environment, delivery }; @@ -194,7 +199,6 @@ export const createServer = ( } = createSessionRecorders(server, session); const toolContext: ServerToolContext = { server, - analysis, session, options: selectedOptions, environment, @@ -203,6 +207,7 @@ export const createServer = ( activeTarget, recordEvidence, recordEvidenceWithUnknown, + withAdmittedAnalysis: withAdmittedAnalysis(source), }; registerBinaryAnalysisTools(toolContext); const previousOnclose = server.server.onclose; @@ -344,39 +349,34 @@ const createSessionRecorders = ( recordEvidence: session === undefined ? undefined - : (evidence: Parameters[0]) => { - const recorded = session.recordEvidence(evidence); - return recorded; - }, + : (evidence: Parameters[0]) => + session.recordEvidence(evidence), recordEvidenceWithUnknown: session === undefined ? undefined : ( evidence: Parameters[0], input: Parameters[1], - ) => { - const recorded = session.recordEvidenceWithUnknown(evidence, input); - return recorded; - }, + ) => session.recordEvidenceWithUnknown(evidence, input), }); interface ServerToolContext extends ReturnType { readonly server: EvidenceMcpServer; - readonly analysis: AnalysisOperationPort; readonly session: BinarySessionPort | undefined; readonly options: CreateServerOptions; readonly environment: Readonly; readonly logger: Logger; + readonly withAdmittedAnalysis: WithAdmittedAnalysis; } const registerBinaryAnalysisTools = ({ server, - analysis, session, logger, activeTarget, recordEvidence, recordEvidenceWithUnknown, + withAdmittedAnalysis, }: ServerToolContext): void => { const recordUnknown = session === undefined @@ -388,9 +388,10 @@ const registerBinaryAnalysisTools = ({ activeTarget, recordEvidence, recordUnknown, + withAdmittedAnalysis, }; - registerOfficialTools(server, analysis, analysisOptions); - registerEnhancedTools(server, analysis, { + registerOfficialTools(server, analysisOptions); + registerEnhancedTools(server, { ...analysisOptions, analysisProfile: session === undefined ? undefined : () => session.analysisProfile(), @@ -403,15 +404,15 @@ const registerBinaryAnalysisTools = ({ ? undefined : (input) => session.recordWorkflowSnapshot(input), }); - const evidenceOptions = { logger, activeTarget, recordEvidence }; - registerNativeTools(server, analysis, evidenceOptions); - registerArtifactTools(server, analysis, { - ...evidenceOptions, - }); - registerManagedTools(server, analysis, { - ...evidenceOptions, - session, - }); + const evidenceOptions = { + logger, + activeTarget, + recordEvidence, + withAdmittedAnalysis, + }; + registerNativeTools(server, evidenceOptions); + registerArtifactTools(server, evidenceOptions); + registerManagedTools(server, evidenceOptions); if (session !== undefined) registerManagedWorkflowTools(server, { logger, diff --git a/src/server/registerArtifactTools.ts b/src/server/registerArtifactTools.ts index 898584567..c3509bae6 100644 --- a/src/server/registerArtifactTools.ts +++ b/src/server/registerArtifactTools.ts @@ -1,7 +1,6 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; -import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import type { Logger } from "pino"; @@ -11,14 +10,14 @@ import { artifactInspectionResultSchema } from "../domain/artifactInspection.js" /** Register deterministic artifact inventory and safe extraction operations. */ export const registerArtifactTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, options: { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; + readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis; }, ): void => { - registerEvidenceTools(server, analysis, ARTIFACT_TOOL_CONTRACTS, { + registerEvidenceTools(server, ARTIFACT_TOOL_CONTRACTS, { ...options, sourceEvidence: (operation, result) => operation === "inspect_artifact" diff --git a/src/server/registerCloseLifecycleTool.ts b/src/server/registerCloseLifecycleTool.ts index 8f5384380..828a0dfdb 100644 --- a/src/server/registerCloseLifecycleTool.ts +++ b/src/server/registerCloseLifecycleTool.ts @@ -22,23 +22,25 @@ export const registerCloseLifecycleTool = ({ const progress = mcpProgressReporter(context); const snapshotPath = input.snapshot_path; if (snapshotPath === undefined) { - await reportLifecycleStart(progress, closeContract.name); - const closed = await logToolExecution(logger, closeContract.name, () => + // Enqueue the lifecycle transition before awaiting progress transport so + // a later open request cannot overtake this close. + const closing = logToolExecution(logger, closeContract.name, () => session.close({ progress }), ); + await reportLifecycleStart(progress, closeContract.name); + const closed = await closing; await reportLifecycleEnd(progress, closeContract.name, closed.ok); return server.delivery.toCallToolResult(closed, closeContract); } + const closing = logToolExecution(logger, closeContract.name, () => + session.closeWithSnapshot(snapshotPath, input.overwrite, { progress }), + ); await reportLifecycleStart( progress, closeContract.name, "saving snapshot; closing provider", ); - const closed = await logToolExecution(logger, closeContract.name, () => - session.closeWithSnapshot(snapshotPath, input.overwrite, { - progress, - }), - ); + const closed = await closing; await reportLifecycleEnd(progress, closeContract.name, closed.ok); return server.delivery.toCallToolResult( closed.ok ? ok({ ...closed.value }) : closed, diff --git a/src/server/registerEnhancedTools.ts b/src/server/registerEnhancedTools.ts index e972353d6..e1e27c127 100644 --- a/src/server/registerEnhancedTools.ts +++ b/src/server/registerEnhancedTools.ts @@ -28,9 +28,11 @@ import { mcpProgressReporter } from "./mcpProgress.js"; import { logToolExecution } from "./toolLogging.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; import { executeFunctionAnalysisEvidence } from "../application/FunctionAnalysisEvidence.js"; +import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; /** Optional session services used by enhanced tool registration. */ export interface EnhancedToolRegistration { + readonly withAdmittedAnalysis: WithAdmittedAnalysis; readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly analysisProfile: @@ -52,7 +54,6 @@ export interface EnhancedToolRegistration { // oxlint-disable-next-line max-lines-per-function -- direct SDK calls retain each schema-handler type correlation. export const registerEnhancedTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, options: EnhancedToolRegistration, ): void => { const registration = { ...options, delivery: server.delivery }; @@ -76,7 +77,7 @@ export const registerEnhancedTools = ( traceNativeValues.name, toolRegistrationOptions(traceNativeValues), (input, context) => - executeEnhancedTool(analysis, registration, traceNativeValues, { + executeEnhancedTool(registration, traceNativeValues, { validatedCall: { name: "trace_native_values", input }, context, }), @@ -85,7 +86,7 @@ export const registerEnhancedTools = ( nativeDispatchMetadata.name, toolRegistrationOptions(nativeDispatchMetadata), (input, context) => - executeEnhancedTool(analysis, registration, nativeDispatchMetadata, { + executeEnhancedTool(registration, nativeDispatchMetadata, { validatedCall: { name: "inspect_native_dispatch_metadata", input }, context, }), @@ -94,7 +95,7 @@ export const registerEnhancedTools = ( objcClasses.name, toolRegistrationOptions(objcClasses), (input, context) => - executeEnhancedTool(analysis, registration, objcClasses, { + executeEnhancedTool(registration, objcClasses, { validatedCall: { name: "get_objc_classes", input }, context, }), @@ -103,7 +104,7 @@ export const registerEnhancedTools = ( objcProtocols.name, toolRegistrationOptions(objcProtocols), (input, context) => - executeEnhancedTool(analysis, registration, objcProtocols, { + executeEnhancedTool(registration, objcProtocols, { validatedCall: { name: "get_objc_protocols", input }, context, }), @@ -112,7 +113,7 @@ export const registerEnhancedTools = ( batchDecompile.name, toolRegistrationOptions(batchDecompile), (input, context) => - executeEnhancedTool(analysis, registration, batchDecompile, { + executeEnhancedTool(registration, batchDecompile, { validatedCall: { name: "batch_decompile", input }, context, }), @@ -121,7 +122,7 @@ export const registerEnhancedTools = ( callGraph.name, toolRegistrationOptions(callGraph), (input, context) => - executeEnhancedTool(analysis, registration, callGraph, { + executeEnhancedTool(registration, callGraph, { validatedCall: { name: "get_call_graph", input }, context, }), @@ -130,7 +131,7 @@ export const registerEnhancedTools = ( swiftTypes.name, toolRegistrationOptions(swiftTypes), (input, context) => - executeEnhancedTool(analysis, registration, swiftTypes, { + executeEnhancedTool(registration, swiftTypes, { validatedCall: { name: "analyze_swift_types", input }, context, }), @@ -139,7 +140,7 @@ export const registerEnhancedTools = ( xrefsToName.name, toolRegistrationOptions(xrefsToName), (input, context) => - executeEnhancedTool(analysis, registration, xrefsToName, { + executeEnhancedTool(registration, xrefsToName, { validatedCall: { name: "find_xrefs_to_name", input }, context, }), @@ -148,7 +149,7 @@ export const registerEnhancedTools = ( binaryOverview.name, toolRegistrationOptions(binaryOverview), (input, context) => - executeEnhancedTool(analysis, registration, binaryOverview, { + executeEnhancedTool(registration, binaryOverview, { validatedCall: { name: "binary_overview", input }, context, }), @@ -157,7 +158,7 @@ export const registerEnhancedTools = ( analyzeFunction.name, toolRegistrationOptions(analyzeFunction), (input, context) => - executeEnhancedTool(analysis, registration, analyzeFunction, { + executeEnhancedTool(registration, analyzeFunction, { validatedCall: { name: "analyze_function", input }, context, }), @@ -166,7 +167,7 @@ export const registerEnhancedTools = ( inspectNativeApi.name, toolRegistrationOptions(inspectNativeApi), (input, context) => - executeEnhancedTool(analysis, registration, inspectNativeApi, { + executeEnhancedTool(registration, inspectNativeApi, { validatedCall: { name: "inspect_native_api", input }, context, }), @@ -175,7 +176,7 @@ export const registerEnhancedTools = ( traceFeature.name, toolRegistrationOptions(traceFeature), (input, context) => - executeEnhancedTool(analysis, registration, traceFeature, { + executeEnhancedTool(registration, traceFeature, { validatedCall: { name: "trace_feature", input }, context, }), @@ -184,7 +185,7 @@ export const registerEnhancedTools = ( traceCallPath.name, toolRegistrationOptions(traceCallPath), (input, context) => - executeEnhancedTool(analysis, registration, traceCallPath, { + executeEnhancedTool(registration, traceCallPath, { validatedCall: { name: "trace_call_path", input }, context, }), @@ -193,7 +194,7 @@ export const registerEnhancedTools = ( traceNativeUiAction.name, toolRegistrationOptions(traceNativeUiAction), (input, context) => - executeEnhancedTool(analysis, registration, traceNativeUiAction, { + executeEnhancedTool(registration, traceNativeUiAction, { validatedCall: { name: "trace_native_ui_action", input }, context, }), @@ -201,7 +202,6 @@ export const registerEnhancedTools = ( }; const executeEnhancedTool = async ( - analysis: AnalysisOperationPort, registration: EnhancedToolRegistration & { readonly delivery: ToolResultDelivery; }, @@ -211,76 +211,86 @@ const executeEnhancedTool = async ( readonly context: ServerContext; }, ): Promise => { - const { validatedCall, context } = request; - const name = validatedCall.name; - const progress = mcpProgressReporter(context); - await progress.report({ - phase: name, - completed: 0, - total: 1, - message: "started", - }); - const parsedInput = validatedCall.input; - const parameters = jsonParameters(parsedInput); - if (name === "analyze_function") - return executeFunctionTool(analysis, registration, contract, { - context, - parameters, - }); - const services = new EnhancedTools({ - execute: (operation, operationParameters, executionOptions) => - analysis.execute(operation, operationParameters, { - ...executionOptions, - progress, - }), - }); - const result = await logToolExecution(registration.logger, name, () => - services.executeValidated(validatedCall, context.mcpReq.signal), - ); - await progress.report({ - phase: name, - completed: 1, - total: 1, - message: result.ok ? "completed" : "failed", - terminal: true, - }); - if (result.ok) { - const evidence = createWorkflowEvidence({ - target: registration.activeTarget?.(), - operation: name, - parameters, - result: result.value, - upstreamProfile: registration.analysisProfile?.(), - }); - const recorded = registration.recordEvidence?.(evidence); - if (recorded !== undefined && !recorded.ok) - return registration.delivery.toCallToolResult(recorded, contract); - if ( - name !== "trace_native_ui_action" && - registration.allowsSnapshotReplay?.(name) === true - ) { - const workflowRecord = workflowSnapshotRecord(evidence, name); - if (workflowRecord !== undefined) { - const snapshot = registration.recordWorkflowSnapshot?.(workflowRecord); - if (snapshot !== undefined && !snapshot.ok) - return registration.delivery.toCallToolResult(snapshot, contract); + const admitted = await registration.withAdmittedAnalysis( + request.validatedCall.name, + request.context.mcpReq.signal, + async (admittedAnalysis) => { + const { validatedCall, context } = request; + const name = validatedCall.name; + const progress = mcpProgressReporter(context); + await progress.report({ + phase: name, + completed: 0, + total: 1, + message: "started", + }); + const parsedInput = validatedCall.input; + const parameters = jsonParameters(parsedInput); + if (name === "analyze_function") + return executeFunctionTool(admittedAnalysis, registration, contract, { + context, + parameters, + }); + const services = new EnhancedTools({ + execute: (operation, operationParameters, executionOptions) => + admittedAnalysis.execute(operation, operationParameters, { + ...executionOptions, + progress, + }), + }); + const result = await logToolExecution(registration.logger, name, () => + services.executeValidated(validatedCall, context.mcpReq.signal), + ); + await progress.report({ + phase: name, + completed: 1, + total: 1, + message: result.ok ? "completed" : "failed", + terminal: true, + }); + if (result.ok) { + const evidence = createWorkflowEvidence({ + target: registration.activeTarget?.(), + operation: name, + parameters, + result: result.value, + upstreamProfile: registration.analysisProfile?.(), + }); + const recorded = registration.recordEvidence?.(evidence); + if (recorded !== undefined && !recorded.ok) + return registration.delivery.toCallToolResult(recorded, contract); + if ( + name !== "trace_native_ui_action" && + registration.allowsSnapshotReplay?.(name) === true + ) { + const workflowRecord = workflowSnapshotRecord(evidence, name); + if (workflowRecord !== undefined) { + const snapshot = + registration.recordWorkflowSnapshot?.(workflowRecord); + if (snapshot !== undefined && !snapshot.ok) + return registration.delivery.toCallToolResult(snapshot, contract); + } + } + const unknowns = recordWorkflowUnknowns({ + name, + result: result.value, + evidenceId: evidence.evidence_id, + recordUnknown: registration.recordUnknown, + }); + if (!unknowns.ok) + return registration.delivery.toCallToolResult(unknowns, contract); + return registration.delivery.toEvidenceToolResult( + evidence, + contract, + recorded, + ); } - } - const unknowns = recordWorkflowUnknowns({ - name, - result: result.value, - evidenceId: evidence.evidence_id, - recordUnknown: registration.recordUnknown, - }); - if (!unknowns.ok) - return registration.delivery.toCallToolResult(unknowns, contract); - return registration.delivery.toEvidenceToolResult( - evidence, - contract, - recorded, - ); - } - return registration.delivery.toCallToolResult(result, contract); + return registration.delivery.toCallToolResult(result, contract); + }, + ); + return admitted.ok + ? admitted.value + : registration.delivery.toCallToolResult(admitted, contract); }; const executeFunctionTool = async ( diff --git a/src/server/registerEvidenceTools.ts b/src/server/registerEvidenceTools.ts index d03111745..c03079c9c 100644 --- a/src/server/registerEvidenceTools.ts +++ b/src/server/registerEvidenceTools.ts @@ -14,11 +14,16 @@ import { mcpProgressReporter } from "./mcpProgress.js"; import { logToolExecution } from "./toolLogging.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js"; +import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; interface EvidenceToolRegistration { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; + readonly withAdmittedAnalysis: WithAdmittedAnalysis; + readonly analysisForAdmission?: ( + analysis: AnalysisOperationPort, + ) => AnalysisOperationPort; readonly sourceEvidence?: ( operation: Exclude, result: import("../domain/jsonValue.js").JsonValue, @@ -28,7 +33,6 @@ interface EvidenceToolRegistration { /** Register provider-backed contracts that return atomic Evidence observations. */ export const registerEvidenceTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, contracts: readonly ToolContract>[], options: EvidenceToolRegistration, ): void => { @@ -37,68 +41,84 @@ export const registerEvidenceTools = ( contract.name, toolRegistrationOptions(contract), async (input, context) => { - const progress = mcpProgressReporter(context); - await progress.report({ - phase: contract.name, - completed: 0, - total: 1, - message: "started", - }); - const parameters = jsonObjectSchema.parse(input); - const executionParameters = - contract.name === "extract_artifact" - ? { - ...parameters, - output_root: createArtifactExtractionDestination(), - } - : parameters; - const execution = await logToolExecution( - options.logger, + const admitted = await options.withAdmittedAnalysis( contract.name, - () => - analysis.execute(contract.name, executionParameters, { - signal: context.mcpReq.signal, - progress, - }), - ); - await progress.report({ - phase: contract.name, - completed: 1, - total: 1, - message: execution.ok ? "completed" : "failed", - terminal: true, - }); - if (!execution.ok) - return server.delivery.toCallToolResult(execution, contract); - const sourceEvidence = - options.sourceEvidence?.(contract.name, execution.value.result) ?? []; - const evidence = createEvidence( - execution.value.subject ?? options.activeTarget?.(), - execution.value.provider, - { - operation: contract.name, - parameters, - result: execution.value.result, - ...(execution.value.analysisProfile === undefined - ? {} - : { analysisProfile: execution.value.analysisProfile }), - rawResult: execution.value.rawResult, - limitations: execution.value.limitations, - locations: execution.value.locations, - evidenceLinks: sourceEvidence.map(({ evidence_id: id }) => id), + context.mcpReq.signal, + async (admittedAnalysis) => { + const analysis = + options.analysisForAdmission?.(admittedAnalysis) ?? + admittedAnalysis; + const progress = mcpProgressReporter(context); + await progress.report({ + phase: contract.name, + completed: 0, + total: 1, + message: "started", + }); + const parameters = jsonObjectSchema.parse(input); + const executionParameters = + contract.name === "extract_artifact" + ? { + ...parameters, + output_root: createArtifactExtractionDestination(), + } + : parameters; + const execution = await logToolExecution( + options.logger, + contract.name, + () => + analysis.execute(contract.name, executionParameters, { + signal: context.mcpReq.signal, + progress, + }), + ); + await progress.report({ + phase: contract.name, + completed: 1, + total: 1, + message: execution.ok ? "completed" : "failed", + terminal: true, + }); + if (!execution.ok) + return server.delivery.toCallToolResult(execution, contract); + const sourceEvidence = + options.sourceEvidence?.(contract.name, execution.value.result) ?? + []; + const evidence = createEvidence( + execution.value.subject ?? options.activeTarget?.(), + execution.value.provider, + { + operation: contract.name, + parameters, + result: execution.value.result, + ...(execution.value.analysisProfile === undefined + ? {} + : { analysisProfile: execution.value.analysisProfile }), + rawResult: execution.value.rawResult, + limitations: execution.value.limitations, + locations: execution.value.locations, + evidenceLinks: sourceEvidence.map(({ evidence_id: id }) => id), + }, + ); + for (const source of sourceEvidence) { + const sourceRecorded = options.recordEvidence?.(source); + if (sourceRecorded !== undefined && !sourceRecorded.ok) + return server.delivery.toCallToolResult( + sourceRecorded, + contract, + ); + } + const recorded = options.recordEvidence?.(evidence); + return server.delivery.toEvidenceToolResult( + evidence, + contract, + recorded, + ); }, ); - for (const source of sourceEvidence) { - const sourceRecorded = options.recordEvidence?.(source); - if (sourceRecorded !== undefined && !sourceRecorded.ok) - return server.delivery.toCallToolResult(sourceRecorded, contract); - } - const recorded = options.recordEvidence?.(evidence); - return server.delivery.toEvidenceToolResult( - evidence, - contract, - recorded, - ); + return admitted.ok + ? admitted.value + : server.delivery.toCallToolResult(admitted, contract); }, ); } diff --git a/src/server/registerManagedTools.ts b/src/server/registerManagedTools.ts index 74b7cac35..f54f2981f 100644 --- a/src/server/registerManagedTools.ts +++ b/src/server/registerManagedTools.ts @@ -2,7 +2,6 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; -import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; import { MANAGED_TOOL_CONTRACTS } from "../contracts/managed/managedToolContracts.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; @@ -15,16 +14,17 @@ import { isManagedToolName } from "../contracts/managed/managedToolContracts.js" /** Register execution-free managed PE/CLI inspection. */ export const registerManagedTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, options: { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; - readonly session: BinarySessionPort | undefined; + readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis; }, ): void => { let selectedManagedPath: string | undefined; - const managedAnalysis: AnalysisOperationPort = { + const analysisForAdmission = ( + analysis: AnalysisOperationPort, + ): AnalysisOperationPort => ({ execute: async (operation, parameters, executionOptions) => { if (!isManagedToolName(operation)) return analysis.execute(operation, parameters, executionOptions); @@ -57,11 +57,9 @@ export const registerManagedTools = ( selectedManagedPath = requestedPath; return execution; }, - }; - registerEvidenceTools( - server, - managedAnalysis, - MANAGED_TOOL_CONTRACTS, - options, - ); + }); + registerEvidenceTools(server, MANAGED_TOOL_CONTRACTS, { + ...options, + analysisForAdmission, + }); }; diff --git a/src/server/registerNativeTools.ts b/src/server/registerNativeTools.ts index 35d5029a0..ba244a8e3 100644 --- a/src/server/registerNativeTools.ts +++ b/src/server/registerNativeTools.ts @@ -1,7 +1,6 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; -import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import type { Logger } from "pino"; @@ -10,12 +9,13 @@ import { registerEvidenceTools } from "./registerEvidenceTools.js"; /** Register provider-neutral static inspection operations. */ export const registerNativeTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, options: { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; + readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis; }, -): void => { - registerEvidenceTools(server, analysis, NATIVE_TOOL_CONTRACTS, options); -}; +): void => + registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, { + ...options, + }); diff --git a/src/server/registerOfficialTools.ts b/src/server/registerOfficialTools.ts index 14c18337d..dcb5b10ab 100644 --- a/src/server/registerOfficialTools.ts +++ b/src/server/registerOfficialTools.ts @@ -17,77 +17,92 @@ import type { Logger } from "pino"; import { mcpProgressReporter } from "./mcpProgress.js"; import { logToolExecution } from "./toolLogging.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; +import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; /** Optional session services used by direct tool registration. */ export interface OfficialToolRegistration { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; + readonly withAdmittedAnalysis: WithAdmittedAnalysis; } /** Register direct bridge proxies, preserving MCP cancellation and typed errors. */ export const registerOfficialTools = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, options: OfficialToolRegistration, ): void => { for (const contract of OFFICIAL_TOOL_CONTRACTS) { - registerOfficialTool(server, analysis, contract, { + registerOfficialTool(server, contract, { logger: options.logger, activeTarget: options.activeTarget, recordEvidence: options.recordEvidence, + withAdmittedAnalysis: options.withAdmittedAnalysis, }); } }; const registerOfficialTool = ( server: EvidenceMcpServer, - analysis: AnalysisOperationPort, contract: (typeof OFFICIAL_TOOL_CONTRACTS)[number], registration: { readonly logger: Logger; readonly activeTarget: (() => BinaryTarget | undefined) | undefined; readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; + readonly withAdmittedAnalysis: WithAdmittedAnalysis; }, ): void => { server.registerTool( contract.name, toolRegistrationOptions(contract), async (input: unknown, context: ServerContext) => { - const arguments_ = jsonObjectSchema.parse( - contract.inputSchema.parse(input), - ); - const progress = mcpProgressReporter(context); - const result = await runOfficialOperation( - analysis, - contract, - arguments_, - { - logger: registration.logger, - signal: context.mcpReq.signal, - progress, + const admitted = await registration.withAdmittedAnalysis( + contract.name, + context.mcpReq.signal, + async (admittedAnalysis) => { + const arguments_ = jsonObjectSchema.parse( + contract.inputSchema.parse(input), + ); + const progress = mcpProgressReporter(context); + const result = await runOfficialOperation( + admittedAnalysis, + contract, + arguments_, + { + logger: registration.logger, + signal: context.mcpReq.signal, + progress, + }, + ); + if (!result.ok) { + return server.delivery.toCallToolResult(result, contract); + } + const evidence = createEvidence( + result.value.subject ?? registration.activeTarget?.(), + result.value.provider, + { + operation: contract.name, + parameters: arguments_, + result: result.value.result, + ...(result.value.analysisProfile === undefined + ? {} + : { analysisProfile: result.value.analysisProfile }), + rawResult: result.value.rawResult, + limitations: result.value.limitations, + locations: result.value.locations, + }, + ); + const recorded = registration.recordEvidence?.(evidence); + return server.delivery.toEvidenceToolResult( + evidence, + contract, + recorded, + ); }, ); - if (!result.ok) { - return server.delivery.toCallToolResult(result, contract); - } - const evidence = createEvidence( - result.value.subject ?? registration.activeTarget?.(), - result.value.provider, - { - operation: contract.name, - parameters: arguments_, - result: result.value.result, - ...(result.value.analysisProfile === undefined - ? {} - : { analysisProfile: result.value.analysisProfile }), - rawResult: result.value.rawResult, - limitations: result.value.limitations, - locations: result.value.locations, - }, - ); - const recorded = registration.recordEvidence?.(evidence); - return server.delivery.toEvidenceToolResult(evidence, contract, recorded); + return admitted.ok + ? admitted.value + : server.delivery.toCallToolResult(admitted, contract); }, ); }; diff --git a/src/server/registerSessionTools.ts b/src/server/registerSessionTools.ts index d4dc0b48a..5d0b1bf38 100644 --- a/src/server/registerSessionTools.ts +++ b/src/server/registerSessionTools.ts @@ -232,20 +232,36 @@ const registerContextTools = ( navigationContract.name, toolRegistrationOptions(navigationContract), async (input, context) => { - return server.delivery.toCallToolResult( - await getNavigationContext(session, input, context.mcpReq.signal), - navigationContract, + const admitted = await session.withAdmittedAnalysis( + navigationContract.name, + context.mcpReq.signal, + async (analysis) => + server.delivery.toCallToolResult( + await getNavigationContext(analysis, input, context.mcpReq.signal), + navigationContract, + ), ); + return admitted.ok + ? admitted.value + : server.delivery.toCallToolResult(admitted, navigationContract); }, ); server.registerTool( addressContract.name, toolRegistrationOptions(addressContract), async (input, context) => { - return server.delivery.toCallToolResult( - await inspectAddressContext(session, input, context.mcpReq.signal), - addressContract, + const admitted = await session.withAdmittedAnalysis( + addressContract.name, + context.mcpReq.signal, + async (analysis) => + server.delivery.toCallToolResult( + await inspectAddressContext(analysis, input, context.mcpReq.signal), + addressContract, + ), ); + return admitted.ok + ? admitted.value + : server.delivery.toCallToolResult(admitted, addressContract); }, ); }; diff --git a/tests/acceptance/nonBinaryComposition.test.ts b/tests/acceptance/nonBinaryComposition.test.ts index b333db20e..d2409723f 100644 --- a/tests/acceptance/nonBinaryComposition.test.ts +++ b/tests/acceptance/nonBinaryComposition.test.ts @@ -17,11 +17,14 @@ const connect = async (environment: NodeJS.ProcessEnv) => { const session = createTestBinarySession(() => { throw new Error("Target-free analysis must not acquire a deep provider"); }); - const server = createServer(session, session, { - androidAnalysis: createAndroidAnalysisProvider(environment), - firmwareAnalysis: createFirmwareAnalysisProvider(environment), - javascriptRecovery: createJavaScriptRecoveryProvider(environment), - }); + const server = createServer( + { kind: "session", session }, + { + androidAnalysis: createAndroidAnalysisProvider(environment), + firmwareAnalysis: createFirmwareAnalysisProvider(environment), + javascriptRecovery: createJavaScriptRecoveryProvider(environment), + }, + ); const client = new Client({ name: "composition-parity", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/acceptance/webModuleCli.test.ts b/tests/acceptance/webModuleCli.test.ts index 2171d54ca..36675d794 100644 --- a/tests/acceptance/webModuleCli.test.ts +++ b/tests/acceptance/webModuleCli.test.ts @@ -48,9 +48,12 @@ cliTest( const session = createTestBinarySession(() => { throw new Error("no binary acquisition"); }); - const server = createServer(session, session, { - webModuleTrace: createWebModuleTraceService(environment), - }); + const server = createServer( + { kind: "session", session }, + { + webModuleTrace: createWebModuleTraceService(environment), + }, + ); const client = new Client({ name: "module-cli-parity", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/advertisedPatternsVMode.test.ts b/tests/boundary/mcp/advertisedPatternsVMode.test.ts index 595c356fc..024c42d12 100644 --- a/tests/boundary/mcp/advertisedPatternsVMode.test.ts +++ b/tests/boundary/mcp/advertisedPatternsVMode.test.ts @@ -34,7 +34,7 @@ it("advertises portable NUL escapes and patterns that compile in all JS modes", const session = createTestBinarySession(() => { throw new Error("No deep provider may start for a schema projection"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "advertised-patterns", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index 9d188e6c0..3edeffba7 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -27,8 +27,7 @@ const connect = async (binaryLayout?: BinaryLayoutService) => { throw new Error("selected views must not start a deep provider"); }); const server = createServer( - session, - session, + { kind: "session", session }, binaryLayout === undefined ? {} : { binaryLayout }, ); const client = new Client({ name: "analysis-view-mcp", version: "1" }); diff --git a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts index 7405c30c2..9241bf471 100644 --- a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts +++ b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts @@ -26,7 +26,7 @@ it("inspects a standalone keyed archive through MCP with original object identit ), ); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "keyed-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -119,7 +119,7 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as await writeFile(archive, await writer.close()); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-inline-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts index 5b786a2dd..ee180a37f 100644 --- a/tests/boundary/mcp/artifactMcp.test.ts +++ b/tests/boundary/mcp/artifactMcp.test.ts @@ -47,7 +47,7 @@ it.each([ } const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "asar-integrity-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -117,7 +117,7 @@ it("extracts an active archive through MCP when requested", async () => { await writeFile(archive, await zip.close()); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-extract-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -166,7 +166,7 @@ it("extracts a macOS app bundle through MCP", async () => { await writeFile(join(contents, "MacOS", "Fixture"), header); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-extract-app-test", version: "1", @@ -225,7 +225,7 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n await writeFile(archive, bytes); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "asar-continue-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -326,7 +326,7 @@ it("rejects inline artifact Evidence whose content does not match its ID", async execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-authority-test", version: "1", @@ -364,7 +364,7 @@ it("compares inline inventory Evidence without prior session calls", async () => execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-ownership-test", version: "1", @@ -411,7 +411,7 @@ it("returns full artifact graphs inline and compares changed inventories", async ); await writeFile(changedArchive, await changedWriter.close()); const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "artifact-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts index 4570bbb93..d825d96de 100644 --- a/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/binaryDiagnosticsMcp.test.ts @@ -21,7 +21,10 @@ it("advertises exact valid schemas and records inline layout without a binary ta const session = createTestBinarySession(() => { throw new Error("deep provider must not start"); }); - const server = createServer(session, session, { binaryLayout: service }); + const server = createServer( + { kind: "session", session }, + { binaryLayout: service }, + ); const client = new Client({ name: "binary-layout-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/browserMcp.test.ts b/tests/boundary/mcp/browserMcp.test.ts index aa3fa853f..8e31e4839 100644 --- a/tests/boundary/mcp/browserMcp.test.ts +++ b/tests/boundary/mcp/browserMcp.test.ts @@ -291,13 +291,16 @@ const connectBrowser = async () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session, { - browserObservation: new CdpBrowserProvider(), - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 0, - }), - }); + const server = createServer( + { kind: "session", session }, + { + browserObservation: new CdpBrowserProvider(), + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 0, + }), + }, + ); const client = new Client({ name: "browser-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/browserScenarioMcp.test.ts b/tests/boundary/mcp/browserScenarioMcp.test.ts index 41736f952..c6bfdd6e1 100644 --- a/tests/boundary/mcp/browserScenarioMcp.test.ts +++ b/tests/boundary/mcp/browserScenarioMcp.test.ts @@ -175,14 +175,17 @@ describe("browser scenario MCP tool", () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(ok(null)), })); - const server = createServer(session, session, { - browserObservation: new CdpBrowserProvider(), - browserScenarioCapture: provider, - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 0, - }), - }); + const server = createServer( + { kind: "session", session }, + { + browserObservation: new CdpBrowserProvider(), + browserScenarioCapture: provider, + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 0, + }), + }, + ); const client = new Client({ name: "browser-scenario-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/bundleComparisonMcp.test.ts b/tests/boundary/mcp/bundleComparisonMcp.test.ts index 0ea1006b3..9fb00e768 100644 --- a/tests/boundary/mcp/bundleComparisonMcp.test.ts +++ b/tests/boundary/mcp/bundleComparisonMcp.test.ts @@ -152,7 +152,7 @@ const connect = async () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "bundle-comparison-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/clientCapabilities.test.ts b/tests/boundary/mcp/clientCapabilities.test.ts index 323f79980..a8acc0048 100644 --- a/tests/boundary/mcp/clientCapabilities.test.ts +++ b/tests/boundary/mcp/clientCapabilities.test.ts @@ -23,7 +23,7 @@ describe("per-request client capability reporting", () => { "reports the negotiated capability %j", async (capabilities, form, url) => { const session = createTestBinarySession(createCacheProvider([])); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "capabilities-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -61,7 +61,7 @@ describe("initialize-scoped client metadata", () => { meta?: Record, ) => { const session = createTestBinarySession(createCacheProvider([])); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client( { name: "initialize-test", version: "2" }, { capabilities }, diff --git a/tests/boundary/mcp/comparisonUnknownsMcp.test.ts b/tests/boundary/mcp/comparisonUnknownsMcp.test.ts index 7e07713fe..bf950f83b 100644 --- a/tests/boundary/mcp/comparisonUnknownsMcp.test.ts +++ b/tests/boundary/mcp/comparisonUnknownsMcp.test.ts @@ -16,7 +16,7 @@ const connect = async () => { const session = createTestBinarySession(() => { throw new Error("Evidence comparison must not launch a provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "comparison-unknowns", version: "1" }); onTestFinished(async () => { await Promise.allSettled([client.close(), server.close(), session.close()]); diff --git a/tests/boundary/mcp/dylibResolutionMcp.test.ts b/tests/boundary/mcp/dylibResolutionMcp.test.ts index 34db785e3..4f2d70aab 100644 --- a/tests/boundary/mcp/dylibResolutionMcp.test.ts +++ b/tests/boundary/mcp/dylibResolutionMcp.test.ts @@ -25,7 +25,7 @@ const withClient = async ( verify: (client: Client) => Promise, ): Promise => { const session = createTestBinarySession(new ArtifactProvider(process.env)); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "dylib-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts index efa700ba1..4910fd9f8 100644 --- a/tests/boundary/mcp/electronMcp.test.ts +++ b/tests/boundary/mcp/electronMcp.test.ts @@ -72,13 +72,16 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session, { - electronObservation: new CdpElectronProvider(), - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 1, - }), - }); + const server = createServer( + { kind: "session", session }, + { + electronObservation: new CdpElectronProvider(), + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 1, + }), + }, + ); const client = new Client({ name: "electron-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -197,13 +200,16 @@ it("runs active Electron scenarios with selected paths and inferred working dire execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session, { - electronActiveObservation: provider, - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 0, - }), - }); + const server = createServer( + { kind: "session", session }, + { + electronActiveObservation: provider, + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 0, + }), + }, + ); const client = new Client({ name: "electron-active-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -279,12 +285,15 @@ it("exposes the target-free static JavaScript application workflow", async () => execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session, { - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 1, - }), - }); + const server = createServer( + { kind: "session", session }, + { + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 1, + }), + }, + ); const client = new Client({ name: "electron-static-mcp-test", version: "1", diff --git a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts index 958852001..7662c8234 100644 --- a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts +++ b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts @@ -186,7 +186,7 @@ afterEach(async () => { }); const connect = async (analysis: AnalysisOperationPort = fixturePort()) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "enhanced-test", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/enhancedToolsHarness.ts b/tests/boundary/mcp/enhancedToolsHarness.ts index 26bb194ab..1fa41151b 100644 --- a/tests/boundary/mcp/enhancedToolsHarness.ts +++ b/tests/boundary/mcp/enhancedToolsHarness.ts @@ -24,7 +24,7 @@ export const inventory = (values: Readonly>) => export const resources: Array<{ close(): Promise }> = []; export const connect = async (analysis: AnalysisOperationPort) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "enhanced-test", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/evidenceBundleInline.test.ts b/tests/boundary/mcp/evidenceBundleInline.test.ts index 597b47a94..adb95ef8f 100644 --- a/tests/boundary/mcp/evidenceBundleInline.test.ts +++ b/tests/boundary/mcp/evidenceBundleInline.test.ts @@ -18,7 +18,7 @@ it("returns the complete session Evidence bundle in the tool result", async () = close: () => Promise.resolve(resultOk(null)), })); expect(session.recordEvidence(evidence).ok).toBe(true); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "inline-evidence-bundle", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/evidenceExportCancellation.test.ts b/tests/boundary/mcp/evidenceExportCancellation.test.ts index 2a7e2c40b..ca084f813 100644 --- a/tests/boundary/mcp/evidenceExportCancellation.test.ts +++ b/tests/boundary/mcp/evidenceExportCancellation.test.ts @@ -28,7 +28,7 @@ it.each([false, true])( }, ); expect(session.recordEvidence(evidence).ok).toBe(true); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "evidence-export-cancellation", version: "1", diff --git a/tests/boundary/mcp/evmInterfaceMcp.test.ts b/tests/boundary/mcp/evmInterfaceMcp.test.ts index d1d7c94bb..d197c2742 100644 --- a/tests/boundary/mcp/evmInterfaceMcp.test.ts +++ b/tests/boundary/mcp/evmInterfaceMcp.test.ts @@ -20,7 +20,10 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit const session = createTestBinarySession(() => { throw new Error("deep provider must not start"); }); - const server = createServer(session, session, { evmInterface: service }); + const server = createServer( + { kind: "session", session }, + { evmInterface: service }, + ); const client = new Client({ name: "evm-interface-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/firmwareMcp.test.ts b/tests/boundary/mcp/firmwareMcp.test.ts index a18fccdcf..4e3b7761a 100644 --- a/tests/boundary/mcp/firmwareMcp.test.ts +++ b/tests/boundary/mcp/firmwareMcp.test.ts @@ -16,9 +16,12 @@ it("executes named firmware contracts with inline Evidence and no native binary const session = createTestBinarySession(() => { throw new Error("Firmware inspection must not acquire a native provider"); }); - const server = createServer(session, session, { - firmwareAnalysis: fixture.provider, - }); + const server = createServer( + { kind: "session", session }, + { + firmwareAnalysis: fixture.provider, + }, + ); const client = new Client({ name: "firmware-regression", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/functionComparisonMcp.test.ts b/tests/boundary/mcp/functionComparisonMcp.test.ts index e5965a522..429bca334 100644 --- a/tests/boundary/mcp/functionComparisonMcp.test.ts +++ b/tests/boundary/mcp/functionComparisonMcp.test.ts @@ -39,7 +39,7 @@ describe("function comparison reconstruction MCP integration", () => { authority: left.authority, }, ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "function-verification-test", version: "1", @@ -140,7 +140,7 @@ describe("function comparison MCP integration", () => { expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right).ok).toBe( true, ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "function-comparison-test", version: "1", @@ -196,7 +196,7 @@ describe("function comparison MCP integration", () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "function-link-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -240,7 +240,7 @@ describe("function comparison MCP integration", () => { ); session.recordEvidence(wrong); session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "function-authority-test", version: "1", diff --git a/tests/boundary/mcp/ghidraMcpHarness.ts b/tests/boundary/mcp/ghidraMcpHarness.ts index 473179102..cbfbb7019 100644 --- a/tests/boundary/mcp/ghidraMcpHarness.ts +++ b/tests/boundary/mcp/ghidraMcpHarness.ts @@ -52,7 +52,10 @@ export const connectGhidraMcp = async ( const session = composeBinarySession( new AnalysisProviderRegistry([provider]), ); - const server = createServer(session, session, { logger: silentLogger }); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); const mcp = new Client({ name, version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/investigationAnalysisMcp.test.ts b/tests/boundary/mcp/investigationAnalysisMcp.test.ts index a9b9d4765..752f81bc3 100644 --- a/tests/boundary/mcp/investigationAnalysisMcp.test.ts +++ b/tests/boundary/mcp/investigationAnalysisMcp.test.ts @@ -324,7 +324,7 @@ const connected = async () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "investigation-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/javascriptAnalysisCancellation.test.ts b/tests/boundary/mcp/javascriptAnalysisCancellation.test.ts index 7325ef763..3325b1706 100644 --- a/tests/boundary/mcp/javascriptAnalysisCancellation.test.ts +++ b/tests/boundary/mcp/javascriptAnalysisCancellation.test.ts @@ -51,7 +51,7 @@ it("stops a cancelled SDK request on the server, retains prior Evidence, and acc }, }, ); - const server = createServer(session, session, { logger }); + const server = createServer({ kind: "session", session }, { logger }); const client = new Client({ name: "javascript-cancellation", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/javascriptRecoveryMcp.test.ts b/tests/boundary/mcp/javascriptRecoveryMcp.test.ts index e22891ae6..4c1bd9809 100644 --- a/tests/boundary/mcp/javascriptRecoveryMcp.test.ts +++ b/tests/boundary/mcp/javascriptRecoveryMcp.test.ts @@ -17,9 +17,12 @@ it.skipIf(process.platform !== "linux" || process.arch !== "x64")( const session = createTestBinarySession(() => { throw new Error("no binary provider should start"); }); - const server = createServer(session, session, { - javascriptRecovery: fixture.provider, - }); + const server = createServer( + { kind: "session", session }, + { + javascriptRecovery: fixture.provider, + }, + ); const client = new Client({ name: "recovery-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/javascriptRuntimeObservationMcp.test.ts b/tests/boundary/mcp/javascriptRuntimeObservationMcp.test.ts index 9682998e8..77c9d59ec 100644 --- a/tests/boundary/mcp/javascriptRuntimeObservationMcp.test.ts +++ b/tests/boundary/mcp/javascriptRuntimeObservationMcp.test.ts @@ -179,13 +179,16 @@ const createObservationClient = async ( execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session, { - javascriptRuntimeObservation: new V8InspectorProvider(), - availabilityPolicy: () => ({ - processCaptureEnabled: false, - investigationInputRoots: 0, - }), - }); + const server = createServer( + { kind: "session", session }, + { + javascriptRuntimeObservation: new V8InspectorProvider(), + availabilityPolicy: () => ({ + processCaptureEnabled: false, + investigationInputRoots: 0, + }), + }, + ); const client = new Client({ name: "v8-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/keyedArchiveNumberMetadataMcp.test.ts b/tests/boundary/mcp/keyedArchiveNumberMetadataMcp.test.ts index 5d16e87f4..4a40a3064 100644 --- a/tests/boundary/mcp/keyedArchiveNumberMetadataMcp.test.ts +++ b/tests/boundary/mcp/keyedArchiveNumberMetadataMcp.test.ts @@ -27,7 +27,9 @@ mcpTest.for(archiveNumberMetadataCases)( onTestFinished(async () => { await session.close(); }); - const client = await mcp.connect(createServer(session, session)); + const client = await mcp.connect( + createServer({ kind: "session", session }), + ); const opened = await client.callTool({ name: "open_binary", arguments: { path: fixture.path }, diff --git a/tests/boundary/mcp/largeToolResult.test.ts b/tests/boundary/mcp/largeToolResult.test.ts index 8b61f9be6..7453db0d0 100644 --- a/tests/boundary/mcp/largeToolResult.test.ts +++ b/tests/boundary/mcp/largeToolResult.test.ts @@ -49,20 +49,20 @@ const callPseudoCode = async ( recordEvidence, delivery, ); - registerOfficialTools( - server, - { - execute: () => - Promise.resolve( - ok(createAnalysisExecution(payload, provider, { rawResult })), - ), - }, - { - logger: silentLogger, - activeTarget: undefined, - recordEvidence, - }, - ); + registerOfficialTools(server, { + logger: silentLogger, + activeTarget: undefined, + recordEvidence, + withAdmittedAnalysis: async (_operationName, _signal, operation) => + ok( + await operation({ + execute: () => + Promise.resolve( + ok(createAnalysisExecution(payload, provider, { rawResult })), + ), + }), + ), + }); const client = new Client({ name: "complete-evidence-client", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/managedMcp.test.ts b/tests/boundary/mcp/managedMcp.test.ts index 762651708..6a985d7ec 100644 --- a/tests/boundary/mcp/managedMcp.test.ts +++ b/tests/boundary/mcp/managedMcp.test.ts @@ -14,7 +14,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js"; import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js"; import type { BinarySession } from "../../../src/application/binary/BinarySession.js"; -import type { BinaryTarget } from "../../../src/domain/binaryTargetTypes.js"; import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js"; @@ -35,8 +34,7 @@ it("runs every managed static inspection independently of an active native targe new ManagedStaticProvider(), ]); const server = createServer( - session, - sessionWithUnrelatedNativeTarget(session), + { kind: "session", session }, { availabilityPolicy: () => ({ processCaptureEnabled: false, @@ -133,8 +131,7 @@ it("opens a managed PE and executes the managed static provider through MCP", as new ManagedStaticProvider(), ]); const server = createServer( - session, - sessionWithUnrelatedNativeTarget(session), + { kind: "session", session }, { availabilityPolicy: () => ({ processCaptureEnabled: false, @@ -288,28 +285,6 @@ const inspectManagedStaticWorkflow = async ( return members; }; -const sessionWithUnrelatedNativeTarget = ( - session: BinarySession, -): BinarySession => { - const nativeTarget: BinaryTarget = { - kind: "executable", - format: "pe", - path: "C:\\Windows\\System32\\notepad.exe", - sha256: "a".repeat(64), - architecture: "x86_64", - availableArchitectures: ["x86_64"], - executableRole: "application", - managed: false, - }; - return new Proxy(session, { - get(target, property, receiver) { - if (property === "activeTarget") return () => nativeTarget; - const value: unknown = Reflect.get(target, property, receiver); - return typeof value === "function" ? value.bind(target) : value; - }, - }); -}; - const methodFrom = (members: Record) => z .array( diff --git a/tests/boundary/mcp/mobileApplicationGraphMcp.test.ts b/tests/boundary/mcp/mobileApplicationGraphMcp.test.ts index 7c8abe33c..80173eba8 100644 --- a/tests/boundary/mcp/mobileApplicationGraphMcp.test.ts +++ b/tests/boundary/mcp/mobileApplicationGraphMcp.test.ts @@ -27,7 +27,7 @@ async function connect() { const session = createTestBinarySession(() => { throw new Error("mobile graph projection must not launch a provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "mobile-application-graph-test", version: "1", diff --git a/tests/boundary/mcp/nativeCallObservationMcp.test.ts b/tests/boundary/mcp/nativeCallObservationMcp.test.ts index 284d6ce43..cecd3b2f4 100644 --- a/tests/boundary/mcp/nativeCallObservationMcp.test.ts +++ b/tests/boundary/mcp/nativeCallObservationMcp.test.ts @@ -90,7 +90,7 @@ it("routes observe_native_calls through MCP with schema-checked input and output const session = createTestBinarySession( new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer), ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "native-calls-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -233,7 +233,7 @@ it.each([ const session = createTestBinarySession( new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer), ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "native-calls-partial-mcp-test", version: "1", diff --git a/tests/boundary/mcp/nativeDemangleMcp.test.ts b/tests/boundary/mcp/nativeDemangleMcp.test.ts index 75b22572c..71f7732a5 100644 --- a/tests/boundary/mcp/nativeDemangleMcp.test.ts +++ b/tests/boundary/mcp/nativeDemangleMcp.test.ts @@ -40,7 +40,9 @@ describe.skipIf(process.platform !== "darwin")( onTestFinished(async () => { await session.close(); }); - const client = await mcp.connect(createServer(session, session)); + const client = await mcp.connect( + createServer({ kind: "session", session }), + ); const opened = await client.callTool({ name: "open_binary", arguments: { path: target }, diff --git a/tests/boundary/mcp/nativeInputContracts.test.ts b/tests/boundary/mcp/nativeInputContracts.test.ts index 4429f8863..f8a9d183d 100644 --- a/tests/boundary/mcp/nativeInputContracts.test.ts +++ b/tests/boundary/mcp/nativeInputContracts.test.ts @@ -35,7 +35,7 @@ const resources: Array<{ close(): Promise }> = []; const connect = async ( execute: AnalysisOperationPort["execute"], ): Promise => { - const server = createServer({ execute }); + const server = createServer({ kind: "fixed", analysis: { execute } }); const client = new Client({ name: "native-contract-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts b/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts index 4468491c2..5576fccef 100644 --- a/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts +++ b/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts @@ -22,7 +22,7 @@ it("rejects changed signature targets through MCP and accepts reopening the new const session = createTestBinarySession( new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"), ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "signature-binding-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/officialArguments.test.ts b/tests/boundary/mcp/officialArguments.test.ts index 943f6893e..ff0284ac0 100644 --- a/tests/boundary/mcp/officialArguments.test.ts +++ b/tests/boundary/mcp/officialArguments.test.ts @@ -20,7 +20,7 @@ import { } from "../../fixtures/binarySession.js"; const connect = async (analysis: AnalysisOperationPort) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "argument-parity", version: "1.0.0" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/officialTools.test.ts b/tests/boundary/mcp/officialTools.test.ts index 95b741313..70fbf8587 100644 --- a/tests/boundary/mcp/officialTools.test.ts +++ b/tests/boundary/mcp/officialTools.test.ts @@ -72,7 +72,7 @@ afterEach(async () => { }); const connect = async (analysis: AnalysisOperationPort) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "contract-test", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/optionalProviderIsolation.test.ts b/tests/boundary/mcp/optionalProviderIsolation.test.ts index 7ede38874..eb8f64fd1 100644 --- a/tests/boundary/mcp/optionalProviderIsolation.test.ts +++ b/tests/boundary/mcp/optionalProviderIsolation.test.ts @@ -60,10 +60,12 @@ const boot = async (factories: OptionalObservationFactories) => { await run({ env: {}, loadOptionalProviders: async () => loaded, - createServer: (analysis, selectedSession, options) => { - session = selectedSession; + createServer: (source, options) => { + if (source.kind !== "session") + throw new Error("Expected a session-owned server source"); + session = source.session; // A configured policy cannot hide an actual adapter loading failure. - return createServer(analysis, selectedSession, { + return createServer(source, { ...options, availabilityPolicy: () => ({ processCaptureEnabled: true, diff --git a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts index 3377277ae..7667b1ffb 100644 --- a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts @@ -44,7 +44,7 @@ const connect = async () => { const session = createTestBinarySession(() => { throw new Error("Process comparison must not launch a provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "process-comparison-test", version: "1" }); onTestFinished(async () => { await Promise.allSettled([client.close(), server.close(), session.close()]); diff --git a/tests/boundary/mcp/processEvidenceIdentityMcp.test.ts b/tests/boundary/mcp/processEvidenceIdentityMcp.test.ts index 9fc252995..fb20dd79b 100644 --- a/tests/boundary/mcp/processEvidenceIdentityMcp.test.ts +++ b/tests/boundary/mcp/processEvidenceIdentityMcp.test.ts @@ -57,7 +57,7 @@ const connectedComparison = async () => { const session = createTestBinarySession(() => { throw new Error("Process comparison must not launch a provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "process-evidence-identity", version: "1", diff --git a/tests/boundary/mcp/processTraceAdaptersParity.test.ts b/tests/boundary/mcp/processTraceAdaptersParity.test.ts index 913d640cd..7f9d3d9c3 100644 --- a/tests/boundary/mcp/processTraceAdaptersParity.test.ts +++ b/tests/boundary/mcp/processTraceAdaptersParity.test.ts @@ -126,10 +126,7 @@ describe("declared trace adapter parity", () => { ); expect(session.recordEvidence(left).ok).toBe(true); expect(session.recordEvidence(right).ok).toBe(true); - const server = createServer( - { execute: () => Promise.resolve(ok(null)) }, - session, - ); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "trace-parity", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/progressMcp.test.ts b/tests/boundary/mcp/progressMcp.test.ts index ff0a94216..31c537a92 100644 --- a/tests/boundary/mcp/progressMcp.test.ts +++ b/tests/boundary/mcp/progressMcp.test.ts @@ -12,7 +12,7 @@ describe("ordinary MCP progress and cancellation", () => { const analysis: AnalysisOperationPort = { execute: () => Promise.resolve(observed("0x1000")), }; - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "progress-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -59,7 +59,7 @@ describe("ordinary MCP progress and cancellation", () => { return err(new AnalysisCancelledError(operation)); }, }; - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "cancellation-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/promptMcp.test.ts b/tests/boundary/mcp/promptMcp.test.ts index b8399906a..0f9725c83 100644 --- a/tests/boundary/mcp/promptMcp.test.ts +++ b/tests/boundary/mcp/promptMcp.test.ts @@ -42,7 +42,7 @@ afterEach(async () => { describe("guided prompts over MCP", () => { it("lists and renders all workflows without changing the tool inventory", async () => { const session = fixtureSession(); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); const toolsBeforePrompts = (await client.listTools()).tools; @@ -96,7 +96,7 @@ describe("guided prompts over MCP", () => { const session = fixtureSession(() => { executions += 1; }); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); for (const contract of PROMPT_CONTRACTS) { @@ -126,7 +126,7 @@ describe("guided prompts over MCP", () => { const session = fixtureSession(() => { executions += 1; }); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); for (const contract of PROMPT_CONTRACTS) @@ -180,7 +180,7 @@ it("preserves caller-selected paths and verbatim crash signals", async () => { await writeFile(targetPath, "owned prompt target", "utf8"); await expect(readFile(targetPath.trim(), "utf8")).rejects.toThrow(); const session = fixtureSession(); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); for (const [name, arguments_] of [ @@ -234,7 +234,7 @@ describe("guided prompt completion registry", () => { }), ).ok, ).toBe(true); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); const result = await client.complete({ @@ -355,7 +355,7 @@ describe("guided prompt completion lifecycle", () => { const session = createTestBinarySession((target) => lifecycleClient(basename(target.path, ".hop"), procedureRequests), ); - const client = await connect(createServer(session, session)); + const client = await connect(createServer({ kind: "session", session })); resources.push(session); expect(await complete(client, "document", "")).toEqual([]); diff --git a/tests/boundary/mcp/providerSelectionMcp.test.ts b/tests/boundary/mcp/providerSelectionMcp.test.ts index 5d30a4e37..1d6cb7b77 100644 --- a/tests/boundary/mcp/providerSelectionMcp.test.ts +++ b/tests/boundary/mcp/providerSelectionMcp.test.ts @@ -43,7 +43,10 @@ describe("provider selection over MCP", () => { candidate("alpha", starts), ]), ); - const server = createServer(session, session, { logger: silentLogger }); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); const mcp = new Client({ name: "provider-selection", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/reconstructionCoverageMcp.test.ts b/tests/boundary/mcp/reconstructionCoverageMcp.test.ts index 50dd2508a..cb3605d14 100644 --- a/tests/boundary/mcp/reconstructionCoverageMcp.test.ts +++ b/tests/boundary/mcp/reconstructionCoverageMcp.test.ts @@ -15,7 +15,7 @@ describe("reconstruction coverage MCP", () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "coverage-mcp-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/reconstructionObligationLedgerMcp.test.ts b/tests/boundary/mcp/reconstructionObligationLedgerMcp.test.ts index 79457903e..572b18d63 100644 --- a/tests/boundary/mcp/reconstructionObligationLedgerMcp.test.ts +++ b/tests/boundary/mcp/reconstructionObligationLedgerMcp.test.ts @@ -13,7 +13,7 @@ describe("reconstruction obligation ledger MCP parity", () => { execute: () => Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "obligation-ledger-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/recordedCrashMcp.test.ts b/tests/boundary/mcp/recordedCrashMcp.test.ts index bdb2b3517..3b809a296 100644 --- a/tests/boundary/mcp/recordedCrashMcp.test.ts +++ b/tests/boundary/mcp/recordedCrashMcp.test.ts @@ -21,7 +21,10 @@ it("advertises exact valid schemas and records inline recorded-core evidence wit const session = createTestBinarySession(() => { throw new Error("deep provider must not start"); }); - const server = createServer(session, session, { recordedCrash: service }); + const server = createServer( + { kind: "session", session }, + { recordedCrash: service }, + ); const client = new Client({ name: "recorded-crash-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts b/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts index 3cf450a7b..ef90cd7e4 100644 --- a/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts +++ b/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts @@ -28,7 +28,7 @@ async function connect() { const session = createTestBinarySession(() => { throw new Error("references must not launch a provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "retained-evidence-test", version: "1" }); resources.push(client, server, session); const [a, b] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts index aa81a8540..09ace062d 100644 --- a/tests/boundary/mcp/serverIdentity.test.ts +++ b/tests/boundary/mcp/serverIdentity.test.ts @@ -206,7 +206,7 @@ describe("server and catalog identity", () => { describe("live server identity over MCP", () => { it("exposes live identity, a stable catalog, and changing availability", async () => { const session = createTestBinarySession(availabilityProvider()); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client( { name: "identity-test", version: "9" }, { @@ -252,7 +252,7 @@ describe("active-target availability over MCP", () => { const session = createTestBinarySession( availabilityProvider(["inspect_macho", "inspect_artifact"]), ); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "availability-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/serverLifecycleMcp.test.ts b/tests/boundary/mcp/serverLifecycleMcp.test.ts index da4520307..6a140befe 100644 --- a/tests/boundary/mcp/serverLifecycleMcp.test.ts +++ b/tests/boundary/mcp/serverLifecycleMcp.test.ts @@ -18,7 +18,7 @@ afterEach(async () => { }); const connect = async (analysis: AnalysisOperationPort) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "integration-test", version: "1.0.0", diff --git a/tests/boundary/mcp/serverUnknownsMcp.test.ts b/tests/boundary/mcp/serverUnknownsMcp.test.ts index fe4dc8499..41fc76c45 100644 --- a/tests/boundary/mcp/serverUnknownsMcp.test.ts +++ b/tests/boundary/mcp/serverUnknownsMcp.test.ts @@ -6,7 +6,6 @@ import { afterEach, expect, it } from "vitest"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import type { AnalysisClient, - AnalysisOperationPort, AnalysisProvider, CapabilityDescriptor, } from "../../../src/application/AnalysisProvider.js"; @@ -62,7 +61,17 @@ const providerWithCapabilities = ( identity: () => identity, capabilities: () => capabilities, createClient: () => ({ - execute: () => Promise.resolve(ok(null)), + execute: (operation) => { + return Promise.resolve( + err( + new AnalysisCapabilityUnavailableError( + "fixture", + operation, + "Decompiler is not installed.", + ), + ), + ); + }, close: () => Promise.resolve(resultOk(null)), }), }; @@ -79,25 +88,10 @@ const structured = (result: CallToolResult): Record => { }; it("does not record capability unavailability without supporting Evidence", async () => { - const received: Array>> = []; - const analysis: AnalysisOperationPort = { - execute: (name, arguments_) => { - received.push(arguments_); - return Promise.resolve( - err( - new AnalysisCapabilityUnavailableError( - "partial", - name, - "Decompiler is not installed.", - ), - ), - ); - }, - }; const session = createTestBinarySession( providerWithCapabilities(["procedure_pseudo_code"]), ); - const server = createServer(analysis, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "unavailable-unknown", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -118,10 +112,9 @@ it("does not record capability unavailability without supporting Evidence", asyn expect(unavailable.isError).toBe(true); expect(structured(unavailable)).toMatchObject({ error: { - category: "unsupported_provider", + category: "unavailable", }, }); - expect(received[0]).toMatchObject({ procedure: "main" }); expect( structured(await client.callTool({ name: "list_unknowns", arguments: {} })), ).toMatchObject({ @@ -166,10 +159,7 @@ it("records capture disagreement as a contradicted unknown", async () => { const rightEvidence = captureEvidence(right); expect(session.recordEvidence(leftEvidence).ok).toBe(true); expect(session.recordEvidence(rightEvidence).ok).toBe(true); - const server = createServer( - { execute: () => Promise.resolve(ok(null)) }, - session, - ); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "comparison-unknown", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/serverWorkflowMcp.test.ts b/tests/boundary/mcp/serverWorkflowMcp.test.ts index aa57b58c4..91a50252a 100644 --- a/tests/boundary/mcp/serverWorkflowMcp.test.ts +++ b/tests/boundary/mcp/serverWorkflowMcp.test.ts @@ -24,7 +24,7 @@ afterEach(async () => { }); const connect = async (analysis: AnalysisOperationPort) => { - const server = createServer(analysis); + const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "integration-test", version: "1.0.0", @@ -107,10 +107,7 @@ it("advertises the complete currently available inventory with a session", async close: () => Promise.resolve(resultOk(null)), }) satisfies AnalysisClient, ); - const server = createServer( - { execute: () => Promise.resolve(ok(null)) }, - session, - ); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "integration-test", version: "1.0.0", diff --git a/tests/boundary/mcp/sessionMcp.test.ts b/tests/boundary/mcp/sessionMcp.test.ts index 33eff767a..302f91ad7 100644 --- a/tests/boundary/mcp/sessionMcp.test.ts +++ b/tests/boundary/mcp/sessionMcp.test.ts @@ -168,10 +168,13 @@ describe("target-free MCP lifecycle", () => { close: () => Promise.resolve(), execute: () => Promise.resolve(ok(null)), }; - const server = createServer(session, session, { - androidAnalysis, - logger: silentLogger, - }); + const server = createServer( + { kind: "session", session }, + { + androidAnalysis, + logger: silentLogger, + }, + ); const mcp = new Client({ name: "status-readiness", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -204,7 +207,10 @@ describe("target-free MCP lifecycle", () => { resolveAnalysisProfile: () => Promise.resolve(resultOk({ profile: SNAPSHOT_PROFILE })), }); - const server = createServer(session, session, { logger: silentLogger }); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); const mcp = new Client({ name: "replaced-target", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/sessionMcpHarness.ts b/tests/boundary/mcp/sessionMcpHarness.ts index 8e45de5c7..45f298c76 100644 --- a/tests/boundary/mcp/sessionMcpHarness.ts +++ b/tests/boundary/mcp/sessionMcpHarness.ts @@ -44,9 +44,12 @@ export const createSessionMcpHarness = async ( resolveAnalysisProfile: () => Promise.resolve(ok({ profile: SNAPSHOT_PROFILE })), }); - const server = createServer(session, session, { - logger: silentLogger, - }); + const server = createServer( + { kind: "session", session }, + { + logger: silentLogger, + }, + ); const mcp = new Client({ name: "session-test", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/webModuleTraceMcp.test.ts b/tests/boundary/mcp/webModuleTraceMcp.test.ts index a8ec5a41d..9db421630 100644 --- a/tests/boundary/mcp/webModuleTraceMcp.test.ts +++ b/tests/boundary/mcp/webModuleTraceMcp.test.ts @@ -21,7 +21,10 @@ it("publishes valid SDK schemas and records the named module trace without a bin const session = createTestBinarySession(() => { throw new Error("binary provider must not start"); }); - const server = createServer(session, session, { webModuleTrace: service }); + const server = createServer( + { kind: "session", session }, + { webModuleTrace: service }, + ); const client = new Client({ name: "module-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/webNetworkCaptureMcp.test.ts b/tests/boundary/mcp/webNetworkCaptureMcp.test.ts index b0ec2fb5c..4bdf06f39 100644 --- a/tests/boundary/mcp/webNetworkCaptureMcp.test.ts +++ b/tests/boundary/mcp/webNetworkCaptureMcp.test.ts @@ -34,7 +34,10 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the const session = createTestBinarySession(() => { throw new Error("Binary provider must not start"); }); - const server = createServer(session, session, { webNetworkCapture: service }); + const server = createServer( + { kind: "session", session }, + { webNetworkCapture: service }, + ); const client = new Client({ name: "historical-capture-contract", version: "1", diff --git a/tests/boundary/mcp/webRuntimeMcp.test.ts b/tests/boundary/mcp/webRuntimeMcp.test.ts index f368ee668..4d99fac75 100644 --- a/tests/boundary/mcp/webRuntimeMcp.test.ts +++ b/tests/boundary/mcp/webRuntimeMcp.test.ts @@ -12,9 +12,12 @@ it("advertises actual SDK schemas, instrumentation effects and session-owned inl const session = createTestBinarySession(() => { throw new Error("Binary provider must not start"); }); - const server = createServer(session, session, { - webRuntime: new WebRuntimeService(recordingWebRuntimePort()), - }); + const server = createServer( + { kind: "session", session }, + { + webRuntime: new WebRuntimeService(recordingWebRuntimePort()), + }, + ); const client = new Client({ name: "web-runtime-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/webSourceLocationMcp.test.ts b/tests/boundary/mcp/webSourceLocationMcp.test.ts index 1bbb4bb0a..df40a0aec 100644 --- a/tests/boundary/mcp/webSourceLocationMcp.test.ts +++ b/tests/boundary/mcp/webSourceLocationMcp.test.ts @@ -26,7 +26,10 @@ it("publishes valid SDK schemas and records the named module trace without a bin const session = createTestBinarySession(() => { throw new Error("binary provider must not start"); }); - const server = createServer(session, session, { webSourceLocation: service }); + const server = createServer( + { kind: "session", session }, + { webSourceLocation: service }, + ); const client = new Client({ name: "module-contract", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts index 9d2635ac7..62369ca4d 100644 --- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts +++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts @@ -13,7 +13,10 @@ import { } from "../../../src/application/AnalysisProvider.js"; import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js"; import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js"; -import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { + createDeferred, + createTestBinarySession, +} from "../../fixtures/binarySession.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js"; import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js"; @@ -37,6 +40,90 @@ afterEach(async () => { await Promise.all(resources.splice(0).map((resource) => resource.close())); }); +describe("MCP composed workflow target admission", () => { + it("keeps a composed result and snapshot on its admitted target across queued close and open", async () => { + const directory = await createTestTempDirectory( + "rea-mcp-admitted-workflow-", + ); + const firstPath = join(directory, "first.hop"); + const secondPath = join(directory, "second.hop"); + const snapshotPath = join(directory, "first-analysis.json"); + await Promise.all([ + writeFile(firstPath, "first target"), + writeFile(secondPath, "second target"), + ]); + const starts: string[] = []; + const calls: string[] = []; + const entered = createDeferred(); + const release = createDeferred(); + const session = createTestBinarySession( + makeProvider(starts, calls, undefined, { entered, release }), + { resolveAnalysisProfile: () => Promise.resolve(ok({ profile })) }, + ); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); + const mcp = new Client({ name: "admitted-workflow", version: "1" }); + const closeStarted = createDeferred(); + mcp.setNotificationHandler("notifications/progress", () => { + closeStarted.resolve(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + resources.push(mcp, server); + await server.connect(serverTransport); + await mcp.connect(clientTransport); + expect( + ( + await mcp.callTool({ + name: "open_binary", + arguments: { path: firstPath }, + }) + ).isError, + ).not.toBe(true); + + const analysisRequest = mcp.callTool({ + name: "binary_overview", + arguments: {}, + }); + await entered.promise; + const closeRequest = mcp.callTool({ + name: "close_binary", + arguments: { snapshot_path: snapshotPath }, + _meta: { progressToken: "close-race" }, + }); + await closeStarted.promise; + const openRequest = mcp.callTool({ + name: "open_binary", + arguments: { path: secondPath }, + }); + release.resolve(); + + const analyzed = await analysisRequest; + expect(analyzed.isError, JSON.stringify(analyzed.content)).not.toBe(true); + const evidence = toolContract("binary_overview").outputSchema.parse( + analyzed.structuredContent, + ); + expect(evidence.analysis_profile).not.toBeNull(); + expect(evidence).toMatchObject({ subject: { local_path: firstPath } }); + const closed = await closeRequest; + expect(closed.isError, JSON.stringify(closed.content)).not.toBe(true); + const snapshot = await readAnalysisSnapshot(snapshotPath); + if (!snapshot.ok) throw snapshot.error; + expect(snapshot.value.workflow_entries).toHaveLength(1); + expect(snapshot.value.evidence_bundle.records).toContainEqual( + expect.objectContaining({ + operation: "binary_overview", + subject: expect.objectContaining({ local_path: firstPath }), + }), + ); + const opened = await openRequest; + expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); + expect(session.activeTarget()?.path).toBe(secondPath); + }); +}); + describe("MCP composed workflow snapshot replay", () => { it("exports an MCP workflow binding and replays its Evidence without provider startup or calls", async () => { const directory = await createTestTempDirectory( @@ -51,7 +138,10 @@ describe("MCP composed workflow snapshot replay", () => { const session = createTestBinarySession(provider, { resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), }); - const server = createServer(session, session, { logger: silentLogger }); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); const mcp = new Client({ name: "workflow-snapshot", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -145,7 +235,10 @@ describe("MCP composed workflow snapshot replay", () => { resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), }, ); - const server = createServer(session, session, { logger: silentLogger }); + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); const mcp = new Client({ name: "live-workflow-snapshot", version: "1.0.0", @@ -190,6 +283,10 @@ const makeProvider = ( starts: string[], calls: string[], liveOperation?: (typeof operations)[number], + pause?: { + readonly entered: ReturnType>; + readonly release: ReturnType>; + }, ): AnalysisProvider => { const capabilities: CapabilityDescriptor[] = operations.map((operation) => ({ operation, @@ -217,6 +314,10 @@ const makeProvider = ( return { execute: async (operation) => { calls.push(operation); + if (operation === "list_documents" && pause !== undefined) { + pause.entered.resolve(); + await pause.release.promise; + } const result = operation === "health" ? null diff --git a/tests/boundary/process/androidAnalysisMcp.test.ts b/tests/boundary/process/androidAnalysisMcp.test.ts index 1cdc4e4f5..de2827fb8 100644 --- a/tests/boundary/process/androidAnalysisMcp.test.ts +++ b/tests/boundary/process/androidAnalysisMcp.test.ts @@ -34,11 +34,11 @@ it("keeps a replacement server usable after the SDK discards its discovery probe factories.push(factory); return { close: async () => undefined }; }, - createServer: (analysis, binary, options) => { + createServer: (source, options) => { if (options?.androidAnalysis === undefined) throw new Error("Expected owned Android provider"); providers.push(options.androidAnalysis); - return createServer(analysis, binary, options); + return createServer(source, options); }, writeStderr: () => undefined, setExitCode: () => undefined, @@ -83,7 +83,10 @@ it("publishes and executes all APK contracts with inline Evidence and no active const session = createTestBinarySession(() => { throw new Error("APK analysis must not acquire a deep binary provider"); }); - const server = createServer(session, session, { androidAnalysis: provider }); + const server = createServer( + { kind: "session", session }, + { androidAnalysis: provider }, + ); const client = new Client({ name: "android-contract-regression", version: "1", @@ -150,7 +153,10 @@ it("cleans an active engine when the MCP client disconnects", async () => { const session = createTestBinarySession(() => { throw new Error("Unexpected native provider acquisition"); }); - const server = createServer(session, session, { androidAnalysis: provider }); + const server = createServer( + { kind: "session", session }, + { androidAnalysis: provider }, + ); const client = new Client({ name: "android-disconnect-regression", version: "1", diff --git a/tests/boundary/process/processCaptureCancellationAdapters.test.ts b/tests/boundary/process/processCaptureCancellationAdapters.test.ts index c3545576f..7a7159e91 100644 --- a/tests/boundary/process/processCaptureCancellationAdapters.test.ts +++ b/tests/boundary/process/processCaptureCancellationAdapters.test.ts @@ -161,7 +161,7 @@ itWithCaptureCapability( }, }, ); - const server = createServer(session, session, { logger }); + const server = createServer({ kind: "session", session }, { logger }); const client = new Client({ name: "process-settlement-cancellation", version: "1", diff --git a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts index 479380579..aa537514f 100644 --- a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts +++ b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts @@ -21,7 +21,7 @@ const captureViaMcp = async (scenario: Record) => { const session = createTestBinarySession(() => { throw new Error("Process capture must not launch a binary provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "filesystem-coverage", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/boundary/process/processSessionMcp.test.ts b/tests/boundary/process/processSessionMcp.test.ts index 3b0a140e5..8b6791df9 100644 --- a/tests/boundary/process/processSessionMcp.test.ts +++ b/tests/boundary/process/processSessionMcp.test.ts @@ -27,9 +27,12 @@ itWithCaptureCapability( "records process residuals linked to capture Evidence", async () => { const session = createTestBinarySession(createCacheProvider([])); - const server = createServer(session, session, { - logger: silentLogger, - }); + const server = createServer( + { kind: "session", session }, + { + logger: silentLogger, + }, + ); const mcp = new Client({ name: "process-unknown", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/process/processTruncationAdapters.test.ts b/tests/boundary/process/processTruncationAdapters.test.ts index bc317d317..34c1ccb3a 100644 --- a/tests/boundary/process/processTruncationAdapters.test.ts +++ b/tests/boundary/process/processTruncationAdapters.test.ts @@ -40,7 +40,7 @@ const capture = async ( const session = createTestBinarySession(() => { throw new Error("Capture must not launch a binary provider"); }); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "truncation-coverage", version: "1" }); onTestFinished(async () => { await client.close(); diff --git a/tests/composition/analysis-sessions/binarySession.test.ts b/tests/composition/analysis-sessions/binarySession.test.ts index bff71bfd5..c0563e06b 100644 --- a/tests/composition/analysis-sessions/binarySession.test.ts +++ b/tests/composition/analysis-sessions/binarySession.test.ts @@ -793,6 +793,37 @@ describe("typed unavailability without dispatching", () => { expect(clients[0]?.closed).toBe(1); expect(clients[1]?.closed).toBe(1); }); + + it("cancels a composed admission queued behind open without invoking it", async () => { + const [first] = await createBinarySessionTargets(); + const health = createDeferred>(); + const session = createTestBinarySession( + () => new ControllableAnalysisClient(health.promise), + ); + const opening = session.open(first); + const controller = new AbortController(); + let invoked = false; + const admitted = session.withAdmittedAnalysis( + "binary_overview", + controller.signal, + async () => { + invoked = true; + return null; + }, + ); + controller.abort(); + await expect(admitted).resolves.toMatchObject({ + ok: false, + error: { + _tag: "AnalysisCancelledError", + operation: "binary_overview", + }, + }); + expect(invoked).toBe(false); + health.resolve(ok(null)); + expect((await opening).ok).toBe(true); + await session.close(); + }); }); describe("active client replacement", () => { diff --git a/tests/fixtures/applicationMcpHarness.ts b/tests/fixtures/applicationMcpHarness.ts index be5b83124..f9e8f38b1 100644 --- a/tests/fixtures/applicationMcpHarness.ts +++ b/tests/fixtures/applicationMcpHarness.ts @@ -19,7 +19,7 @@ export async function createApplicationMcpHarness(): Promise Promise.resolve(observed(null)), close: () => Promise.resolve(resultOk(null)), })); - const server = createServer(session, session); + const server = createServer({ kind: "session", session }); const client = new Client({ name: "application-workflow-test", version: "1", diff --git a/tests/fixtures/contractPresentation.mjs b/tests/fixtures/contractPresentation.mjs index 73b3add91..6f7af51cb 100644 --- a/tests/fixtures/contractPresentation.mjs +++ b/tests/fixtures/contractPresentation.mjs @@ -24,7 +24,7 @@ const { createServer } = await import("../../dist/server/createServer.js"); const config = parseConfig({}); if (!config.ok) throw config.error; const session = createBinarySession(config.value, silentLogger, {}); -const server = createServer(session, session); +const server = createServer({ kind: "session", session }); const client = new Client({ name: "contract-presentation", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); try { diff --git a/tests/process-global/mcpDeliveryEnvironment.test.ts b/tests/process-global/mcpDeliveryEnvironment.test.ts index 32c9061af..6d8751d5e 100644 --- a/tests/process-global/mcpDeliveryEnvironment.test.ts +++ b/tests/process-global/mcpDeliveryEnvironment.test.ts @@ -51,13 +51,19 @@ it("keeps independent server budgets for successful results and oversized errors }; vi.stubEnv("REA_MCP_MAX_RESPONSE_BYTES", String(largeBudget)); - const small = createServer(analysis, undefined, { - environment: smallEnvironment, - }); + const small = createServer( + { kind: "fixed", analysis }, + { + environment: smallEnvironment, + }, + ); vi.stubEnv("REA_MCP_MAX_RESPONSE_BYTES", String(smallBudget)); - const large = createServer(analysis, undefined, { - environment: largeEnvironment, - }); + const large = createServer( + { kind: "fixed", analysis }, + { + environment: largeEnvironment, + }, + ); smallEnvironment.REA_MCP_MAX_RESPONSE_BYTES = "invalid-after-selection"; largeEnvironment.REA_MCP_MAX_RESPONSE_BYTES = String(smallBudget); vi.stubEnv("REA_MCP_MAX_RESPONSE_BYTES", "invalid-ambient-after-selection"); @@ -161,12 +167,12 @@ it("snapshots the runtime-selected environment before optional loading and reuse selected.REA_BROWSER_EXECUTABLE = "/mutated/browser"; return {}; }, - createServer: (analysis, session, options) => { + createServer: (source, options) => { expect(options?.environment?.REA_BROWSER_EXECUTABLE).toBe( "/selected/browser", ); expect(Object.isFrozen(options?.environment)).toBe(true); - const server = createServer(analysis, session, options); + const server = createServer(source, options); observed.push(server); return server; }, From 35f121f4acac821e848c485fb82a2c42f51f6ea1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:21:19 +0800 Subject: [PATCH 015/189] fix: retain completed observations when later analysis steps fail --- docs/android-analysis.md | 6 + src/android/JadxProvider.ts | 38 ++--- src/android/JadxSession.ts | 72 ++++++++-- src/application/DirectAnalysis.ts | 15 +- src/domain/analysisErrorBase.ts | 14 +- .../android/androidPartialObservation.ts | 46 ++++++ .../process/androidAnalysisMcp.test.ts | 134 ++++++++++++++++++ .../directAnalysisSnapshotReplay.test.ts | 51 ++++++- tests/fixtures/android/jadx-mcp.mjs | 14 +- 9 files changed, 350 insertions(+), 40 deletions(-) create mode 100644 src/domain/android/androidPartialObservation.ts diff --git a/docs/android-analysis.md b/docs/android-analysis.md index 63b935da5..efcb05c64 100644 --- a/docs/android-analysis.md +++ b/docs/android-analysis.md @@ -118,6 +118,12 @@ selected overload. Native/abstract methods with no decompiled body report responses remain in Evidence. Source revision is populated only for bytes matching the audited release JAR. +If a later step fails, the error's `details.partial_observation` retains the +selected and resolved APK paths, digest, observed provider identity and versions, +and each upstream request and reply collected before the failure. Failed replies +remain available even when their payload cannot be interpreted. Cancellation +also stops target hashing before provider admission. + These operations do not execute the APK or provide split APK/AAB handling, signature validation, full resource-table semantics, native-library analysis or Android runtime capture. Existing artifact inventory/extraction tools can supply diff --git a/src/android/JadxProvider.ts b/src/android/JadxProvider.ts index e1dc7d4ab..98e798cf7 100644 --- a/src/android/JadxProvider.ts +++ b/src/android/JadxProvider.ts @@ -123,24 +123,25 @@ const cleanup = async ( resources.session = undefined; } catch (cause) { // Retain an uncertain workspace until the caller can resolve process ownership. - return err( - new ProviderCleanupError( - "jadx", - [ - session?.transport.runId ?? "unknown", - ...(root === undefined ? [] : [root.path]), - ], - { - ...diagnostics, - reason: cause instanceof Error ? cause.message : String(cause), - provider_cleanup: - cause instanceof ProviderCleanupError - ? (cause.diagnostics ?? null) - : null, - }, - { cause: previousError ?? cause }, - ), + const error = new ProviderCleanupError( + "jadx", + [ + session?.transport.runId ?? "unknown", + ...(root === undefined ? [] : [root.path]), + ], + { + ...diagnostics, + reason: cause instanceof Error ? cause.message : String(cause), + provider_cleanup: + cause instanceof ProviderCleanupError + ? (cause.diagnostics ?? null) + : null, + }, + { cause: previousError ?? cause }, ); + if (previousError?.partialObservation !== undefined) + error.retainPartialObservation(previousError.partialObservation); + return err(error); } try { await root?.close(); @@ -396,6 +397,9 @@ export class JadxProvider implements AndroidAnalysisPort { signal: options?.signal, session, }); + const partialObservation = session?.partialObservation(); + if (partialObservation !== undefined) + previousError.retainPartialObservation(partialObservation); // Admission can fail before selecting an existing session for execution. root ??= this.#retained?.root; session ??= this.#retained?.session; diff --git a/src/android/JadxSession.ts b/src/android/JadxSession.ts index b8e11f285..13f154b2e 100644 --- a/src/android/JadxSession.ts +++ b/src/android/JadxSession.ts @@ -4,6 +4,7 @@ import { type AnalysisExecution, } from "../application/AnalysisProvider.js"; import type { AndroidRequest } from "../domain/android/androidAnalysis.js"; +import type { AndroidPartialObservation } from "../domain/android/androidPartialObservation.js"; import { AnalysisCapabilityUnavailableError, AnalysisInputError, @@ -35,6 +36,23 @@ export class JadxSession { readonly #client = new Client({ name: "rea-android-adapter", version: "1" }); #loaded: ReturnType | undefined; #connected = false; + #partialContext: + | { + readonly operation: AndroidRequest["operation"]; + readonly selectedPath: string; + readonly target: BinaryTarget; + readonly jarHash: string; + readonly bridgeHash: string; + } + | undefined; + #observedCalls: { + readonly operation: string; + readonly input: Readonly>; + readonly response: JsonValue; + }[] = []; + #serverName: string | null = null; + #serverVersion: string | null = null; + #engineVersion: string | null = null; constructor( options: Omit, @@ -53,6 +71,17 @@ export class JadxSession { readonly signal: AbortSignal; }): Promise { const { request, target, snapshot, jarHash, signal } = context; + this.#partialContext = { + operation: request.operation, + selectedPath: request.input.path, + target, + jarHash, + bridgeHash: context.bridgeHash, + }; + this.#observedCalls = []; + this.#serverName = null; + this.#serverVersion = null; + this.#engineVersion = null; const abort = () => { void this.transport.close().catch(() => undefined); }; @@ -60,12 +89,13 @@ export class JadxSession { try { signal.throwIfAborted(); this.transport.beginOperation(); - const raw: JsonValue[] = []; if (!this.#connected) { await this.#client.connect(this.transport, { timeout: 30_000 }); this.#connected = true; } const server = this.#client.getServerVersion(); + this.#serverName = server?.name ?? null; + this.#serverVersion = server?.version ?? null; if ( server?.name !== JADX_BRIDGE_IDENTITY.name || server.version !== JADX_BRIDGE_IDENTITY.version @@ -75,10 +105,11 @@ export class JadxSession { request.operation, `Expected ${JADX_BRIDGE_IDENTITY.name} ${JADX_BRIDGE_IDENTITY.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`, ); - const tools = this.#tools(request, target, signal, raw); + const tools = this.#tools(request, target, signal); const runtime = jadxRuntimeSchema.parse( await tools.json("rea_jvm_status", {}), ); + this.#engineVersion = runtime.engine_reported_version; if (runtime.engine_reported_version !== JADX_RELEASE.version) throw new AnalysisCapabilityUnavailableError( "jadx", @@ -117,7 +148,7 @@ export class JadxSession { bridge_sha256: context.bridgeHash, jar_sha256: jarHash, loaded, - calls: raw, + calls: this.#observedCalls, }, subject: target, limitations: JADX_LIMITATIONS, @@ -131,6 +162,32 @@ export class JadxSession { } } + /** Facts and upstream replies retained if a later request step fails. */ + partialObservation(): AndroidPartialObservation | undefined { + const context = this.#partialContext; + if (context === undefined) return undefined; + return { + provider_id: "jadx", + operation: context.operation, + target: { + selected_path: context.selectedPath, + path: context.target.path, + sha256: context.target.sha256, + format: "apk", + }, + provider_facts: { + jar_sha256: context.jarHash, + bridge_sha256: context.bridgeHash, + bridge_name: JADX_BRIDGE_IDENTITY.name, + bridge_version: JADX_BRIDGE_IDENTITY.version, + server_name: this.#serverName, + server_version: this.#serverVersion, + engine_version: this.#engineVersion, + }, + calls: this.#observedCalls, + }; + } + /** Whether the selected Java runtime established the REA bridge protocol. */ initialized(): boolean { return this.#connected; @@ -149,7 +206,6 @@ export class JadxSession { request: AndroidRequest, target: BinaryTarget, signal: AbortSignal, - raw: JsonValue[], ): JadxToolPort { const call = async ( name: string, @@ -160,12 +216,10 @@ export class JadxSession { { name, arguments: input }, { timeout: 120_000, signal }, ); + const observedResponse = jsonValueSchema.parse(response); + const call = { operation: name, input, response: observedResponse }; + this.#observedCalls.push(call); const envelope = parseJadxEnvelope(response, request.operation); - raw.push({ - operation: name, - input, - response: jsonValueSchema.parse(response), - }); if (envelope.failed) { if (envelope.text.startsWith("{")) { const failure = jadxInputFailureSchema.safeParse( diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index b51c88656..b24e9cfb2 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -269,7 +269,8 @@ const runAnalysis = async ( }); if (evidence !== undefined) { const recorded = session.recordEvidence(evidence); - if (!recorded.ok) return cliError(recorded.error); + if (!recorded.ok) + return cliError(recorded.error.retainPartialObservation(evidence)); if (isWorkflowEvidenceTool(tool)) { const unknowns = recordWorkflowUnknowns({ name: tool, @@ -277,7 +278,8 @@ const runAnalysis = async ( evidenceId: evidence.evidence_id, recordUnknown: (unknown) => session.recordUnknown(unknown), }); - if (!unknowns.ok) return cliError(unknowns.error); + if (!unknowns.ok) + return cliError(unknowns.error.retainPartialObservation(evidence)); } } if ( @@ -290,7 +292,8 @@ const runAnalysis = async ( const workflowRecord = workflowSnapshotRecord(evidence, tool); if (workflowRecord !== undefined) { const recorded = session.recordWorkflowSnapshot(workflowRecord); - if (!recorded.ok) return cliError(recorded.error); + if (!recorded.ok) + return cliError(recorded.error.retainPartialObservation(evidence)); } } if ( @@ -299,13 +302,15 @@ const runAnalysis = async ( evidence !== undefined ) { const snapshot = session.exportAnalysisSnapshot(); - if (!snapshot.ok) return cliError(snapshot.error); + if (!snapshot.ok) + return cliError(snapshot.error.retainPartialObservation(evidence)); const written = await writeAnalysisSnapshot( snapshot.value, snapshotPath, true, ); - if (!written.ok) return cliError(written.error); + if (!written.ok) + return cliError(written.error.retainPartialObservation(evidence)); } return output; }, diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 97638ecd8..a8449146e 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -77,8 +77,14 @@ export abstract class AnalysisError extends Error { readonly userMessage: string | undefined = undefined; readonly userCategory: "cancelled" | undefined = undefined; readonly executionFailure: string | undefined = undefined; - readonly partialObservation: AnalysisPartialObservation | undefined; + partialObservation: AnalysisPartialObservation | undefined; readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined; + + /** Retain a completed observation when a later step fails. */ + retainPartialObservation(observation: AnalysisPartialObservation): this { + this.partialObservation ??= observation; + return this; + } } import type { PartialProcessCaptureObservation, @@ -90,6 +96,8 @@ import type { ElectronActivePartialObservation } from "./javascript/electronActi import type { JavaScriptRuntimeObservation } from "./javascript/javascriptRuntimeObservation.js"; import type { ArtifactInventoryPartialObservation } from "./artifactPartialObservation.js"; import type { BrowserScenarioPartialObservation } from "./browserScenarioCapture.js"; +import type { Evidence } from "./evidence.js"; +import type { AndroidPartialObservation } from "./android/androidPartialObservation.js"; /** Provider-neutral evidence collected before a typed analysis failure. */ export type AnalysisPartialObservation = @@ -99,4 +107,6 @@ export type AnalysisPartialObservation = | ElectronActivePartialObservation | BrowserScenarioPartialObservation | JavaScriptRuntimeObservation - | ArtifactInventoryPartialObservation; + | ArtifactInventoryPartialObservation + | Evidence + | AndroidPartialObservation; diff --git a/src/domain/android/androidPartialObservation.ts b/src/domain/android/androidPartialObservation.ts new file mode 100644 index 000000000..6a0cbf947 --- /dev/null +++ b/src/domain/android/androidPartialObservation.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; + +import { digestSchema } from "../digests.js"; +import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js"; +import { localPathStringSchema } from "../localPath.js"; + +const operationSchema = z.enum([ + "inspect_android_package", + "search_android_classes", + "inspect_android_class", + "inspect_android_method", + "trace_android_references", +]); + +/** JSON-safe Android provider facts collected before an analysis failure. */ +export const androidPartialObservationSchema = z.strictObject({ + provider_id: z.literal("jadx"), + operation: operationSchema, + target: z.strictObject({ + selected_path: localPathStringSchema, + path: localPathStringSchema, + sha256: digestSchema, + format: z.literal("apk"), + }), + provider_facts: z.strictObject({ + jar_sha256: digestSchema.nullable(), + bridge_sha256: digestSchema.nullable(), + bridge_name: z.string().min(1), + bridge_version: z.string().min(1), + server_name: z.string().nullable(), + server_version: z.string().nullable(), + engine_version: z.string().min(1).nullable(), + }), + calls: z.array( + z.strictObject({ + operation: z.string().min(1), + input: jsonObjectSchema, + response: jsonValueSchema, + }), + ), +}); + +/** JSON-safe Android provider facts retained when analysis fails. */ +export type AndroidPartialObservation = z.infer< + typeof androidPartialObservationSchema +>; diff --git a/tests/boundary/process/androidAnalysisMcp.test.ts b/tests/boundary/process/androidAnalysisMcp.test.ts index de2827fb8..d0179f3c5 100644 --- a/tests/boundary/process/androidAnalysisMcp.test.ts +++ b/tests/boundary/process/androidAnalysisMcp.test.ts @@ -5,7 +5,9 @@ import { expect, it as test, onTestFinished } from "vitest"; import { z } from "zod"; import { access } from "node:fs/promises"; import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/android/androidToolContracts.js"; +import { androidPartialObservationSchema } from "../../../src/domain/android/androidPartialObservation.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { createServer } from "../../../src/server/createServer.js"; import { ToolResultDelivery } from "../../../src/server/toolResult.js"; import { startMcpTransport } from "../../../src/main/transport.js"; @@ -14,6 +16,7 @@ import type { AndroidAnalysisPort } from "../../../src/application/android/Andro import { silentLogger } from "../../../src/logger.js"; import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createJadxProtocolFixture, verifyJadxFixtureCleanup, @@ -148,6 +151,137 @@ it("publishes and executes all APK contracts with inline Evidence and no active await verifyJadxFixtureCleanup(launches); }); +test.each([ + { + scenario: "failed upstream reply", + mode: "tool-error", + errorCode: "execution_failure", + serverName: "rea-jadx-bridge", + serverVersion: "1", + engineVersion: "0.7.1", + calls: [ + { operation: "rea_jvm_status" }, + { operation: "load_apk" }, + { operation: "get_app_info" }, + { + operation: "get_android_manifest", + response: { isError: true }, + }, + ], + containsAmbientEnvironment: false, + }, + { + scenario: "transport error after successful replies", + mode: "rpc-disconnect", + errorCode: "execution_failure", + serverName: "rea-jadx-bridge", + serverVersion: "1", + engineVersion: "0.7.1", + calls: [{ operation: "rea_jvm_status" }, { operation: "load_apk" }], + containsAmbientEnvironment: true, + }, + { + scenario: "empty handshake identity mismatch", + mode: "empty-server-identity", + errorCode: "capability_unavailable", + serverName: "", + serverVersion: "", + engineVersion: null, + calls: [], + containsAmbientEnvironment: true, + }, +])( + "retains Android partial observations for $scenario through MCP", + async ({ + mode, + errorCode, + serverName, + serverVersion, + engineVersion, + calls, + containsAmbientEnvironment, + }) => { + const { provider, apk, launches } = await createJadxProtocolFixture(mode); + const session = createTestBinarySession(() => { + throw new Error("Unexpected native provider acquisition"); + }); + const server = createServer( + { kind: "session", session }, + { androidAnalysis: provider }, + ); + const client = new Client({ + name: "android-partial-observation-regression", + version: "1", + }); + onTestFinished(async () => { + await client.close(); + await server.close(); + await session.close(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const response = await client.callTool({ + name: "inspect_android_package", + arguments: { path: apk }, + }); + const projected = parseMcpToolError(response).error; + expect(projected.code).toBe(errorCode); + const details = z.record(z.string(), z.unknown()).parse(projected.details); + const partial = androidPartialObservationSchema.parse( + details.partial_observation, + ); + expect(partial).toMatchObject({ + provider_id: "jadx", + operation: "inspect_android_package", + target: { selected_path: apk, path: apk, format: "apk" }, + provider_facts: { + bridge_name: "rea-jadx-bridge", + bridge_version: "1", + server_name: serverName, + server_version: serverVersion, + engine_version: engineVersion, + }, + calls, + }); + if (!containsAmbientEnvironment) + expect(JSON.stringify(partial)).not.toContain("JAVA_HOME"); + await client.close(); + await server.close(); + await verifyJadxFixtureCleanup(launches); + }, +); + +it("retains partial JADX replies when owned cleanup also fails", async () => { + const { service, apk } = await createJadxProtocolFixture("cleanup-failure"); + const result = await service.execute("inspect_android_package", { + path: apk, + }); + if (result.ok) throw new Error("Expected the fixture tool to fail"); + + const projected = projectAnalysisError(result.error); + expect(projected.code).toBe("cleanup_incomplete"); + expect(projected.details).toMatchObject({ + cleanup: "incomplete", + execution_failure: "execution_failure", + partial_observation: { + provider_id: "jadx", + operation: "inspect_android_package", + calls: [ + { operation: "rea_jvm_status" }, + { operation: "load_apk" }, + { operation: "get_app_info" }, + { + operation: "get_android_manifest", + response: { isError: true }, + }, + ], + }, + }); +}); + it("cleans an active engine when the MCP client disconnects", async () => { const { provider, apk, launches } = await createJadxProtocolFixture("stall"); const session = createTestBinarySession(() => { diff --git a/tests/composition/directAnalysisSnapshotReplay.test.ts b/tests/composition/directAnalysisSnapshotReplay.test.ts index 0a2332e0d..3fbf5d268 100644 --- a/tests/composition/directAnalysisSnapshotReplay.test.ts +++ b/tests/composition/directAnalysisSnapshotReplay.test.ts @@ -3,6 +3,7 @@ import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { z } from "zod"; import { runDirectAnalysis } from "../../src/application/DirectAnalysis.js"; import type { @@ -18,7 +19,11 @@ import { readAnalysisSnapshot, writeAnalysisSnapshot, } from "../../src/application/binary/AnalysisSnapshotFiles.js"; -import { createEvidence, type Evidence } from "../../src/domain/evidence.js"; +import { + createEvidence, + parseEvidence, + type Evidence, +} from "../../src/domain/evidence.js"; import { createEvidenceBundle } from "../../src/domain/evidenceBundle.js"; import { REA_WORKFLOW_PROVIDER, @@ -646,7 +651,51 @@ describe("snapshot replay provider identity", () => { }); }); +const assertEvidenceSurvivesSnapshotSaveFailure = async (): Promise => { + const directory = await createTestTempDirectory("rea-workflow-save-error-"); + const path = join(directory, "fixture.hop"); + const snapshotPath = join(directory, "missing", "snapshot.json"); + await writeFile(path, "fixture"); + const starts: string[] = []; + const calls: string[] = []; + const provider = makeProvider(starts, calls); + const dependencies: DirectAnalysisDependencies = { + readConfiguration: () => parseConfig({}), + createBinarySession: () => createTestBinarySession(provider), + createManagedBinarySession: () => createTestBinarySession(provider), + }; + + const result = await runDirectAnalysis( + dependencies, + path, + "binary_overview", + {}, + { snapshotPath }, + ); + + expect(result).toMatchObject({ + code: "invalid_request", + details: { + partial_observation: { + operation: "binary_overview", + subject: { local_path: path }, + }, + }, + }); + const partial = z + .object({ + details: z.object({ partial_observation: z.unknown() }), + }) + .parse(result).details.partial_observation; + expect(parseEvidence(partial).operation).toBe("binary_overview"); + expect(calls.toSorted()).toEqual(operations.toSorted()); +}; + describe("workflow snapshot profile and cancellation binding", () => { + it( + "preserves completed Evidence when CLI snapshot persistence fails", + assertEvidenceSurvivesSnapshotSaveFailure, + ); it("does not replay a valid entry from a different workflow profile", async () => { const directory = await createTestTempDirectory("rea-workflow-profile-"); const path = join(directory, "fixture.hop"); diff --git a/tests/fixtures/android/jadx-mcp.mjs b/tests/fixtures/android/jadx-mcp.mjs index 1ab39e866..e95029d53 100644 --- a/tests/fixtures/android/jadx-mcp.mjs +++ b/tests/fixtures/android/jadx-mcp.mjs @@ -6,8 +6,9 @@ import { z } from "zod"; // It is a protocol fixture, not evidence of JADX decompiler support. const mode = process.env.REA_FAKE_JADX_MODE ?? "normal"; const server = new McpServer({ - name: "rea-jadx-bridge", - version: mode === "version" ? "99.0.0" : "1", + name: mode === "empty-server-identity" ? "" : "rea-jadx-bridge", + version: + mode === "empty-server-identity" ? "" : mode === "version" ? "99.0.0" : "1", }); const classes = [ "fixture.Target", @@ -60,16 +61,17 @@ register("load_apk", async ({ path }) => { resources: "full", }); }); -register("get_app_info", () => - json({ +register("get_app_info", () => { + if (mode === "rpc-disconnect") process.exit(17); + return json({ package: "fixture", version_name: "1", version_code: "1", min_sdk: "26", target_sdk: "33", permissions: ["android.permission.INTERNET"], - }), -); + }); +}); register("get_android_manifest", () => { if (mode === "tool-error" || mode === "cleanup-failure") return { From a27794c246b3f11d7f92ae7f6d276718190ab731 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:22:25 +0800 Subject: [PATCH 016/189] fix(artifacts): retain DMG ownership through uncertain attachment --- src/artifacts/NativeDmgArtifactReader.ts | 292 +++++-- src/artifacts/NativeDmgOwnership.ts | 192 +++++ .../native/nativeDmgArtifactReader.test.ts | 769 +++++++++++++++--- 3 files changed, 1065 insertions(+), 188 deletions(-) create mode 100644 src/artifacts/NativeDmgOwnership.ts diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts index c087f987f..9ff38905b 100644 --- a/src/artifacts/NativeDmgArtifactReader.ts +++ b/src/artifacts/NativeDmgArtifactReader.ts @@ -3,9 +3,6 @@ import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import type { Readable } from "node:stream"; -import { parse } from "plist"; -import { z } from "zod"; - import type { ArtifactCommand } from "../domain/artifactGraph.js"; import { ArtifactReaderFailure, @@ -13,32 +10,22 @@ import { type ArtifactReader, } from "./ArtifactReader.js"; import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js"; -import { execFileOutput } from "../process/ExecFileOutput.js"; -const DETACH_TIMEOUT_MS = 120_000; -/** - * Waits before rechecking devices whose detach failed. A related device's - * later detach can eject one, `hdiutil info` can still list an ejected device - * briefly, and a volume can report busy just after it was read. - */ +import { + execFileOutput, + execFileOutputFailure, +} from "../process/ExecFileOutput.js"; +import { + parseNativeDmgAttachOutput, + parseNativeDmgInfo, + resolveNativeDmgOwnership, + type NativeDmgAttachOutput, + type NativeDmgInfo, +} from "./NativeDmgOwnership.js"; +const HDIUTIL_COMMAND_TIMEOUT_MS = 120_000; +// APFS ejects and busy reporting can lag a detach attempt. const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const; const delay = (milliseconds: number): Promise => new Promise((resolve) => setTimeout(resolve, milliseconds)); -const attachOutputSchema = z.object({ - "system-entities": z.array( - z.object({ - "dev-entry": z.string().startsWith("/dev/"), - "mount-point": z.string().optional(), - }), - ), -}); -const infoOutputSchema = z.object({ - images: z.array( - z.object({ - "system-entities": z.array(z.object({ "dev-entry": z.string() })), - }), - ), -}); - /** Narrow host seam for tested, shell-free hdiutil lifecycle operations. */ export interface NativeDmgHost { run( @@ -55,6 +42,27 @@ export interface NativeDmgHost { delay?(milliseconds: number): Promise; } +class NativeDmgCommandFailure extends ArtifactReaderFailure { + readonly processNotStarted: boolean; + + constructor( + reason: ArtifactReaderFailure["reason"], + message: string, + readonly stdout: string, + options?: { + readonly cause?: unknown; + readonly processNotStarted?: boolean; + }, + ) { + super( + reason, + message, + options?.cause === undefined ? undefined : { cause: options.cause }, + ); + this.processNotStarted = options?.processNotStarted ?? false; + } +} + const createSystemHost = ( environment: Readonly, ): NativeDmgHost => ({ @@ -66,26 +74,35 @@ const createSystemHost = ( [...arguments_], { env: environment, + stopSignal: "SIGTERM", ...(options === undefined ? {} : { timeout: options.timeoutMs }), ...(signal === undefined ? {} : { signal }), }, ); return { stdout, stderr, exitCode: 0 }; } catch (cause: unknown) { + const output = execFileOutputFailure(cause); if (cause instanceof Error && cause.name === "AbortError") - throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled"); - const exitCode = processExitCode(cause); + throw new NativeDmgCommandFailure( + "cancelled", + "DMG operation cancelled", + output?.stdout ?? "", + { cause }, + ); + const exitCode = + typeof output?.code === "number" ? output.code : processExitCode(cause); if (exitCode !== undefined) return { - stdout: processOutput(cause, "stdout"), - stderr: processOutput(cause, "stderr"), + stdout: output?.stdout ?? processOutput(cause, "stdout"), + stderr: output?.stderr ?? processOutput(cause, "stderr"), exitCode, cause, }; - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( commandFailureReason(cause, arguments_[0]), `hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`, - { cause }, + output?.stdout ?? "", + { cause, processNotStarted: processNotStarted(cause) }, ); } }, @@ -97,7 +114,13 @@ export class NativeDmgArtifactReader implements ArtifactReader { readonly #provenance: ArtifactCommand[] = []; #directory: DirectoryArtifactReader | undefined; #devices: string[] = []; + #inventoryConfirmedDevices = new Set(); #mountRoot: string | undefined; + #baselineDevices = new Set(); + #attachOutput: NativeDmgAttachOutput | undefined; + #attachOutputReturned = false; + #attachMayHaveMounted = false; + #ownershipUncertainty: string | undefined; private constructor( private readonly path: string, @@ -145,7 +168,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { } async close(): Promise { - let detachFailure: unknown; + let detachFailure = await this.#reconcileAttachState(); let remainingDevices: string[] = []; for (const device of [...this.#devices].reverse()) { const failure = await this.#detach(device); @@ -154,10 +177,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { detachFailure ??= failure; } } - // Detaching a synthesized APFS container also ejects the image that backs - // it, so a device whose own detach failed may be gone by the end of the - // pass, and hdiutil can list an ejected device or report busy briefly. - // Only a device that stays attached through every recheck is a failure. + // APFS container detach may briefly leave its backing image listed. for (const delayMs of DETACH_SETTLE_DELAYS_MS) { if (remainingDevices.length === 0) break; await (this.host.delay ?? delay)(delayMs); @@ -174,7 +194,11 @@ export class NativeDmgArtifactReader implements ArtifactReader { } if (remainingDevices.length === 0) detachFailure = undefined; this.#devices = remainingDevices.reverse(); - if (this.#devices.length === 0 && this.#mountRoot !== undefined) + if ( + this.#devices.length === 0 && + this.#mountRoot !== undefined && + !this.#attachMayHaveMounted + ) await rm(this.#mountRoot, { recursive: true, force: true }).then( () => { this.#mountRoot = undefined; @@ -184,6 +208,12 @@ export class NativeDmgArtifactReader implements ArtifactReader { detachFailure ??= cause; }, ); + if (this.#attachMayHaveMounted) { + detachFailure ??= new Error( + this.#ownershipUncertainty ?? + "hdiutil attachment ownership remains unknown", + ); + } if (detachFailure !== undefined) throw new ArtifactReaderFailure( "unavailable", @@ -194,6 +224,11 @@ export class NativeDmgArtifactReader implements ArtifactReader { reason: failureMessage(detachFailure), resources: [ ...this.#devices.map((device) => `DMG device ${device}`), + ...(this.#attachMayHaveMounted + ? [ + `DMG attachment ownership unknown at mount root ${this.#mountRoot ?? this.path}`, + ] + : []), ...(this.#mountRoot === undefined ? [] : [`DMG mount root ${this.#mountRoot}`]), @@ -207,7 +242,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { async #detach(device: string): Promise { try { await runChecked(this.host, ["detach", device], undefined, { - timeoutMs: DETACH_TIMEOUT_MS, + timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS, }); this.#provenance.push(command(["detach", device], ["mount"])); return undefined; @@ -216,22 +251,31 @@ export class NativeDmgArtifactReader implements ArtifactReader { } } - /** - * Report whether hdiutil still lists a device; unknown state counts as - * attached. Like detach, this cleanup query runs after the inventory - * snapshot has captured provenance, so it is not recorded there. - */ + async #reconcileAttachState(): Promise { + if (!this.#attachMayHaveMounted) return undefined; + try { + await this.#resolveAttachOwnership(); + return undefined; + } catch (cause: unknown) { + this.#ownershipUncertainty = failureMessage(cause); + return cause; + } + } + + /** Treat unknown hdiutil state as attached during cleanup. */ async #isAttached(device: string): Promise { try { - const info = await runChecked(this.host, ["info", "-plist"], undefined, { - timeoutMs: DETACH_TIMEOUT_MS, - }); - const parsed = infoOutputSchema.parse(parse(info.stdout)); - return parsed.images.some((image) => + const parsed = await this.#readInfo(); + const isListed = parsed.images.some((image) => image["system-entities"].some( (entity) => entity["dev-entry"] === device, ), ); + if (isListed) { + this.#inventoryConfirmedDevices.add(device); + return true; + } + return !this.#inventoryConfirmedDevices.has(device); } catch { return true; } @@ -240,8 +284,16 @@ export class NativeDmgArtifactReader implements ArtifactReader { async attach(signal?: AbortSignal): Promise { await runChecked(this.host, ["verify", this.path], signal); this.#provenance.push(command(["verify", this.path], ["read"])); - this.#mountRoot = await realpath(await mkdtemp(join(tmpdir(), "rea-dmg-"))); + const baseline = await this.#readInfo(); + this.#baselineDevices = new Set( + baseline.images.flatMap((image) => + image["system-entities"].map(({ "dev-entry": device }) => device), + ), + ); + const mountRoot = await realpath(await mkdtemp(join(tmpdir(), "rea-dmg-"))); + this.#mountRoot = mountRoot; try { + this.#attachMayHaveMounted = true; const attached = await runChecked( this.host, [ @@ -250,42 +302,37 @@ export class NativeDmgArtifactReader implements ArtifactReader { "-nobrowse", "-plist", "-mountroot", - this.#mountRoot, + mountRoot, this.path, ], signal, + { timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS }, ); - const parsed = attachOutputSchema.parse(parse(attached.stdout)); - const devices = [ - ...new Set( - parsed["system-entities"].map((entity) => entity["dev-entry"]), - ), - ]; - // Detaching an observed whole disk also detaches its partitions. Do not - // subsequently detach the now-unavailable child devices. - this.#devices = devices.filter( - (device) => - !devices.some( - (parent) => - /^\/dev\/disk\d+$/u.test(parent) && - device.startsWith(`${parent}s`) && - /^\d+$/u.test(device.slice(parent.length + 1)), - ), - ); - if (this.#devices.length === 0) + this.#attachOutputReturned = true; + let parsed: NativeDmgAttachOutput; + try { + parsed = parseNativeDmgAttachOutput(attached.stdout); + } catch (cause: unknown) { + throw new ArtifactReaderFailure( + "format", + "hdiutil returned a malformed attachment plist", + { cause }, + ); + } + if (parsed["system-entities"].length === 0) throw new ArtifactReaderFailure( "format", "hdiutil returned no attached devices", ); - for (const entity of parsed["system-entities"]) - if ( - entity["mount-point"] !== undefined && - !entity["mount-point"].startsWith(`${this.#mountRoot}/`) - ) - throw new ArtifactReaderFailure( - "path", - "hdiutil mounted outside the owned root", - ); + this.#attachOutput = parsed; + const ownership = await this.#resolveAttachOwnership(); + if (ownership !== "owned") + throw new ArtifactReaderFailure( + ownership === "unknown" ? "unavailable" : "path", + ownership === "unknown" + ? `DMG attachment ownership is uncertain: ${this.#ownershipUncertainty ?? "no unique mount under the owned root"}` + : "hdiutil did not mount a new image beneath the owned root", + ); this.#provenance.push( command( [ @@ -294,14 +341,26 @@ export class NativeDmgArtifactReader implements ArtifactReader { "-nobrowse", "-plist", "-mountroot", - this.#mountRoot, + mountRoot, this.path, ], ["read", "mount"], ), ); - this.#directory = new DirectoryArtifactReader(this.#mountRoot); + this.#directory = new DirectoryArtifactReader(mountRoot); } catch (cause: unknown) { + if (cause instanceof NativeDmgCommandFailure && cause.stdout !== "") { + try { + this.#attachOutput = parseNativeDmgAttachOutput(cause.stdout); + this.#attachOutputReturned = true; + } catch { + // The original command failure remains primary; fresh info still recovers mounts. + } + } + if (cause instanceof NativeDmgCommandFailure && cause.processNotStarted) { + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + } let cleanupFailure: unknown; try { await this.close(); @@ -319,11 +378,64 @@ export class NativeDmgArtifactReader implements ArtifactReader { throw cause; } } + + async #readInfo(): Promise { + const info = await runChecked(this.host, ["info", "-plist"], undefined, { + timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS, + }); + return parseNativeDmgInfo(info.stdout); + } + + async #resolveAttachOwnership(): Promise<"owned" | "none" | "unknown"> { + const mountRoot = this.#mountRoot; + if (mountRoot === undefined) + throw new Error("DMG mount root is unavailable for ownership discovery"); + const ownership = resolveNativeDmgOwnership({ + info: await this.#readInfo(), + ...(this.#attachOutput === undefined + ? {} + : { attachOutput: this.#attachOutput }), + attachOutputReturned: this.#attachOutputReturned, + mountRoot, + baselineDevices: this.#baselineDevices, + }); + if (ownership.status === "owned") { + this.#devices = [...ownership.devices]; + if (ownership.source === "info") + for (const device of ownership.devices) + this.#inventoryConfirmedDevices.add(device); + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + return "owned"; + } + if (ownership.status === "unknown") { + this.#ownershipUncertainty = ownership.reason; + return "unknown"; + } + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + this.#devices = []; + return "none"; + } } const failureMessage = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause); +const processNotStarted = (cause: unknown): boolean => { + if (!(cause instanceof Error)) return false; + const syscall = Reflect.get(cause, "syscall"); + const code = Reflect.get(cause, "code"); + const errno = Reflect.get(cause, "errno"); + return ( + typeof syscall === "string" && + syscall.startsWith("spawn ") && + (typeof code === "string" || + typeof code === "number" || + typeof errno === "number") + ); +}; + const runChecked = async ( host: NativeDmgHost, arguments_: readonly string[], @@ -336,16 +448,21 @@ const runChecked = async ( } catch (cause: unknown) { if (cause instanceof ArtifactReaderFailure) throw cause; if (cause instanceof Error && cause.name === "AbortError") - throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled", { - cause, - }); - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( + "cancelled", + "DMG operation cancelled", + execFileOutputFailure(cause)?.stdout ?? "", + { cause }, + ); + const output = execFileOutputFailure(cause); + throw new NativeDmgCommandFailure( commandFailureReason(cause, arguments_[0]), `hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure( cause, arguments_, )}`, - { cause }, + output?.stdout ?? "", + { cause, processNotStarted: processNotStarted(cause) }, ); } if (result.exitCode !== 0) { @@ -362,12 +479,13 @@ const runChecked = async ( const details = describeCommandFailure(failure, arguments_); const unknownVerifyFailure = arguments_[0] === "verify" && reason === "unavailable"; - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( reason, unknownVerifyFailure ? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}` : `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`, - result.cause === undefined ? undefined : { cause: result.cause }, + result.stdout, + { cause: result.cause ?? failure }, ); } return { stdout: result.stdout, exitCode: 0 }; diff --git a/src/artifacts/NativeDmgOwnership.ts b/src/artifacts/NativeDmgOwnership.ts new file mode 100644 index 000000000..ac9bf7cff --- /dev/null +++ b/src/artifacts/NativeDmgOwnership.ts @@ -0,0 +1,192 @@ +import { relative, resolve, sep } from "node:path"; + +import { parse } from "plist"; +import { z } from "zod"; + +const systemEntitySchema = z.object({ + "dev-entry": z.string().startsWith("/dev/"), + "mount-point": z.string().optional(), +}); + +const attachOutputSchema = z.object({ + "system-entities": z.array(systemEntitySchema), +}); + +const infoOutputSchema = z.object({ + images: z.array( + z.object({ + "system-entities": z.array(systemEntitySchema), + }), + ), +}); + +/** Parsed hdiutil image inventory used to reconcile owned mount groups. */ +export type NativeDmgInfo = z.output; +/** Parsed hdiutil attach response used to detect unresolved new devices. */ +export type NativeDmgAttachOutput = z.output; + +/** Parse hdiutil's current image inventory. */ +export const parseNativeDmgInfo = (stdout: string): NativeDmgInfo => + infoOutputSchema.parse(parse(stdout)); + +/** Parse hdiutil's attach response while preserving device and mount facts. */ +export const parseNativeDmgAttachOutput = ( + stdout: string, +): NativeDmgAttachOutput => attachOutputSchema.parse(parse(stdout)); + +/** Ownership result for one fresh hdiutil inventory. */ +export type NativeDmgOwnership = + | { + readonly status: "owned"; + readonly devices: readonly string[]; + readonly source: "info" | "attach"; + } + | { readonly status: "none" } + | { readonly status: "unknown"; readonly reason: string }; + +/** Classify only fresh image groups tied to the exclusively owned mount root. */ +export const resolveNativeDmgOwnership = (input: { + readonly info: NativeDmgInfo; + readonly attachOutput?: NativeDmgAttachOutput; + readonly attachOutputReturned: boolean; + readonly mountRoot: string; + readonly baselineDevices: ReadonlySet; +}): NativeDmgOwnership => { + const rootedImages = input.info.images.filter((image) => + image["system-entities"].some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && isBelowRoot(input.mountRoot, mountPoint), + ), + ); + if (rootedImages.length > 1) + return { + status: "unknown", + reason: + "multiple hdiutil image groups report mounts beneath the owned root", + }; + const rootedImage = rootedImages[0]; + if (rootedImage !== undefined) { + const hasOutsideMount = rootedImage["system-entities"].some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && !isBelowRoot(input.mountRoot, mountPoint), + ); + const groupDevices = rootedImage["system-entities"].map( + ({ "dev-entry": device }) => device, + ); + const devices = topLevelDevices(groupDevices); + const overlapsBaseline = groupDevices.some((device) => + input.baselineDevices.has(device), + ); + if (hasOutsideMount || overlapsBaseline || devices.length === 0) + return { + status: "unknown", + reason: hasOutsideMount + ? "the image group contains a mount outside the owned root" + : overlapsBaseline + ? "the image group includes a device present before attachment" + : "the owned mount group contains no detachable device", + }; + return { status: "owned", devices, source: "info" }; + } + + if (input.attachOutputReturned) { + const attachOwnership = ownershipFromAttachOutput( + input.attachOutput, + input.mountRoot, + input.baselineDevices, + ); + if (attachOwnership.status === "owned") { + return attachOwnership; + } + if (attachOwnership.status === "unknown") return attachOwnership; + } + + const newlyListedDevice = input.info.images.some((image) => + image["system-entities"].some( + ({ "dev-entry": device }) => !input.baselineDevices.has(device), + ), + ); + if (newlyListedDevice) + return { + status: "unknown", + reason: + "hdiutil lists devices absent from the pre-attach baseline, but none is tied uniquely to the owned root; ownership is unknown", + }; + return { status: "none" }; +}; + +const ownershipFromAttachOutput = ( + output: NativeDmgAttachOutput | undefined, + mountRoot: string, + baselineDevices: ReadonlySet, +): NativeDmgOwnership => { + if (output === undefined) + return { + status: "unknown", + reason: "hdiutil attach succeeded but its ownership facts were malformed", + }; + const entities = output["system-entities"]; + const hasRootMount = entities.some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && isBelowRoot(mountRoot, mountPoint), + ); + const hasOutsideMount = entities.some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && !isBelowRoot(mountRoot, mountPoint), + ); + const devices = entities.map(({ "dev-entry": device }) => device); + const uniqueDevices = topLevelDevices(devices); + const overlapsBaseline = devices.some((device) => + baselineDevices.has(device), + ); + + if (hasRootMount) { + if (hasOutsideMount || overlapsBaseline || uniqueDevices.length === 0) + return { + status: "unknown", + reason: hasOutsideMount + ? "the attach result includes a mount outside the owned root" + : overlapsBaseline + ? "the attach result includes a device present before attachment" + : "the attach result's owned mount has no detachable device", + }; + return { status: "owned", devices: uniqueDevices, source: "attach" }; + } + + if (devices.length === 0) + return { + status: "unknown", + reason: + "hdiutil attach succeeded without reporting device ownership facts", + }; + if (devices.some((device) => !baselineDevices.has(device))) + return { + status: "unknown", + reason: + "the attach result reports new devices without a mount beneath the owned root", + }; + return { status: "none" }; +}; + +const topLevelDevices = (devices: readonly string[]): string[] => { + const unique = [...new Set(devices)]; + return unique.filter( + (device) => + !unique.some( + (parent) => + /^\/dev\/disk\d+$/u.test(parent) && + device.startsWith(`${parent}s`) && + /^\d+$/u.test(device.slice(parent.length + 1)), + ), + ); +}; + +const isBelowRoot = (root: string, path: string): boolean => { + const child = relative(root, resolve(path)); + return ( + child !== "" && + child !== "." && + child !== ".." && + !child.startsWith(`..${sep}`) + ); +}; diff --git a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts index beb17922e..276db13e1 100644 --- a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts +++ b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts @@ -19,25 +19,141 @@ import { type NativeDmgHost, } from "../../../../src/artifacts/NativeDmgArtifactReader.js"; +const infoPlist = ( + imagePath: string, + entities: { "dev-entry": string; "mount-point"?: string }[], +): string => + build({ + images: [{ "image-path": imagePath, "system-entities": entities }], + }); + +const emptyInfoPlist = build({ images: [] }); + +const attachPlist = ( + entities: { "dev-entry": string; "mount-point"?: string }[], +): string => build({ "system-entities": entities }); + +const createMountFixture = () => { + let root: string | undefined; + onTestFinished(async () => { + if (root !== undefined) await rm(root, { recursive: true, force: true }); + }); + const rememberRoot = (arguments_: readonly string[]): string => { + root = arguments_[arguments_.indexOf("-mountroot") + 1]; + if (root === undefined) throw new Error("missing mount root"); + return root; + }; + return { + root: () => root, + rememberRoot, + async createVolume( + arguments_: readonly string[], + contents?: string, + ): Promise<{ readonly mountRoot: string; readonly mountPoint: string }> { + const mountRoot = rememberRoot(arguments_); + const mountPoint = join(mountRoot, "Fixture"); + await mkdir(mountPoint); + if (contents !== undefined) + await writeFile(join(mountPoint, "hello.txt"), contents); + return { mountRoot, mountPoint }; + }, + }; +}; + +const createOmittedInventoryHost = () => { + const mount = createMountFixture(); + const state: { + calls: string[][]; + mountRoot: string | undefined; + mountPoint: string | undefined; + inventoryMode: "omitted" | "listed"; + attached: boolean; + detachAttempts: number; + } = { + calls: [], + mountRoot: undefined, + mountPoint: undefined, + inventoryMode: "omitted", + attached: false, + detachAttempts: 0, + }; + const host: NativeDmgHost = { + async run(arguments_) { + state.calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + state.attached && + state.inventoryMode === "listed" && + state.mountPoint !== undefined + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk24", + "mount-point": state.mountPoint, + }, + ]) + : emptyInfoPlist, + exitCode: 0, + }; + if (arguments_[0] === "detach") { + state.detachAttempts += 1; + if (state.detachAttempts < 5) + return { stdout: "", stderr: "device busy", exitCode: 1 }; + state.attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + const mounted = await mount.createVolume(arguments_, "owned mount"); + state.mountRoot = mounted.mountRoot; + state.mountPoint = mounted.mountPoint; + state.attached = true; + return { + stdout: attachPlist([ + { "dev-entry": "/dev/disk24", "mount-point": state.mountPoint }, + ]), + exitCode: 0, + }; + }, + delay: () => Promise.resolve(), + }; + return { host, state }; +}; + describe("native DMG artifact reader", () => { it("uses plist attachment metadata and detaches returned devices", async () => { const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; const host: NativeDmgHost = { async run(arguments_) { const args = [...arguments_]; calls.push(args); + if (args[0] === "info") + return { + stdout: attached + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk-fixture", + ...(mountPoint === undefined + ? {} + : { "mount-point": mountPoint }), + }, + ]) + : emptyInfoPlist, + exitCode: 0, + }; + if (args[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } if (args[0] !== "attach") return { stdout: "", exitCode: 0 }; - const mountRoot = args[args.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - const mountPoint = join(mountRoot, "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "hello"); + ({ mountPoint } = await mount.createVolume(args, "hello")); + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk-fixture", "mount-point": mountPoint }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk-fixture", "mount-point": mountPoint }, + ]), exitCode: 0, }; }, @@ -61,7 +177,7 @@ describe("native DMG artifact reader", () => { expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]); }); - it("rejects non-zero results and surfaces detach failure during attach cleanup", async () => { + it("rejects non-zero verification results", async () => { await expect( NativeDmgArtifactReader.create("/tmp/image.dmg", process.env, undefined, { run: () => @@ -77,39 +193,29 @@ describe("native DMG artifact reader", () => { /"arguments":\["verify","\/tmp\/image\.dmg"\].*"exitCode":1.*"stderr":"hdiutil: verify failed - image not recognized"/u, ), }); + }); - let mountRoot: string | undefined; - onTestFinished(async () => { - if (mountRoot !== undefined) - await rm(mountRoot, { recursive: true, force: true }); - }); + it("retains the root and reports unknown ownership when recovery discovery fails", async () => { + const mount = createMountFixture(); const host: NativeDmgHost = { - delay: () => Promise.resolve(), run(arguments_) { - if (arguments_[0] === "detach") - return Promise.reject(new Error("detach failed")); - if (arguments_[0] === "info") + if (arguments_[0] === "info") { + if (mount.root() === undefined) + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); return Promise.resolve({ - stdout: build({ - images: [ - { "system-entities": [{ "dev-entry": "/dev/disk-fixture" }] }, - ], - }), - exitCode: 0, + stdout: "unavailable info plist", + stderr: "hdiutil info failed", + exitCode: 1, }); + } if (arguments_[0] !== "attach") return Promise.resolve({ stdout: "", exitCode: 0 }); - mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); + mount.rememberRoot(arguments_); return Promise.resolve({ - stdout: build({ - "system-entities": [ - { - "dev-entry": "/dev/disk-fixture", - "mount-point": "/tmp/not-owned", - }, - ], - }), + stdout: build({ unexpected: true }), exitCode: 0, }); }, @@ -122,23 +228,459 @@ describe("native DMG artifact reader", () => { host, ), ).rejects.toMatchObject({ + reason: "format", cleanup: { resources: expect.arrayContaining([ - "DMG device /dev/disk-fixture", + expect.stringMatching( + /^DMG attachment ownership unknown at mount root /u, + ), expect.stringMatching(/^DMG mount root /u), ]), }, }); + expect(mount.root()).toBeDefined(); + expect(await realpath(mount.root() ?? "")).toBe(mount.root()); + }); +}); + +describe("DMG attach recovery", () => { + it("keeps attach-output ownership when the first inventory omits the mount", async () => { + const { host, state } = createOmittedInventoryHost(); + const reader = await NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ); + await expect(reader.close()).rejects.toMatchObject({ + reason: "unavailable", + cleanup: { + resources: expect.arrayContaining([ + "DMG device /dev/disk24", + expect.stringMatching(/^DMG mount root /u), + ]), + }, + }); + expect(state.detachAttempts).toBe(4); + expect(await realpath(state.mountRoot ?? "")).toBe(state.mountRoot); + + state.inventoryMode = "listed"; + await reader.close(); + expect(state.detachAttempts).toBe(5); + expect( + await realpath(state.mountRoot ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG rooted ownership isolation", () => { + it("detaches its rooted group while leaving a concurrent foreign image alone", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + let mountPoint: string | undefined; + let ownedAttached = false; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !ownedAttached || mountPoint === undefined + ? emptyInfoPlist + : build({ + images: [ + { + "image-path": "/tmp/image.dmg", + "system-entities": [ + { + "dev-entry": "/dev/disk26", + "mount-point": mountPoint, + }, + ], + }, + { + "image-path": "/tmp/foreign.dmg", + "system-entities": [ + { + "dev-entry": "/dev/disk99", + "mount-point": "/Volumes/Foreign", + }, + ], + }, + ], + }), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + if (arguments_[1] === "/dev/disk26") ownedAttached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + ({ mountPoint } = await mount.createVolume(arguments_)); + ownedAttached = true; + return { + stdout: attachPlist([ + { "dev-entry": "/dev/disk26", "mount-point": mountPoint }, + ]), + exitCode: 0, + }; + }, + }; + + const reader = await NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ); + await reader.close(); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([ + ["detach", "/dev/disk26"], + ]); + expect(ownedAttached).toBe(false); + expect(calls).not.toContainEqual(["detach", "/dev/disk99"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG failed attach output recovery", () => { + it("uses captured attach stdout to recover a failed command's rooted device", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); + if (arguments_[0] === "attach") { + const mountRoot = mount.rememberRoot(arguments_); + return Promise.resolve({ + stdout: attachPlist([ + { + "dev-entry": "/dev/disk25", + "mount-point": join(mountRoot, "Fixture"), + }, + ]), + stderr: "attach interrupted after mounting", + exitCode: 1, + }); + } + return Promise.resolve({ stdout: "", exitCode: 0 }); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toThrow(/hdiutil attach failed/u); + expect(calls).toContainEqual(["detach", "/dev/disk25"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG attach fallback recovery", () => { + it("recovers a mounted image after the attach plist is malformed", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { "dev-entry": "/dev/disk20" }, + { + "dev-entry": "/dev/disk20s1", + "mount-point": mountPoint, + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + ({ mountPoint } = await mount.createVolume( + arguments_, + "recovered mount", + )); + attached = true; + return { stdout: "{invalid plist", exitCode: 0 }; + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toThrow(); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + "detach", + ]); + expect(calls).toContainEqual(["detach", "/dev/disk20"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); + + it("keeps unmounted new devices ambiguous without detaching them", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: + mount.root() === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [{ "dev-entry": "/dev/disk23" }]), + exitCode: 0, + }); + if (arguments_[0] !== "attach") + return Promise.resolve({ stdout: "", exitCode: 0 }); + mount.rememberRoot(arguments_); + return Promise.resolve({ + stdout: attachPlist([{ "dev-entry": "/dev/disk23" }]), + exitCode: 0, + }); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ + reason: "unavailable", + cleanup: { + resources: expect.arrayContaining([ + expect.stringMatching( + /^DMG attachment ownership unknown at mount root /u, + ), + expect.stringMatching(/^DMG mount root /u), + ]), + }, + }); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([]); + expect(await realpath(mount.root() ?? "")).toBe(mount.root()); + }); +}); + +describe("DMG attach cancellation and preexisting mounts", () => { + it("waits for an aborted attach result before discovering and detaching its mount", async () => { + const calls: string[][] = []; + const controller = new AbortController(); + const mount = createMountFixture(); + let markAttachStarted = (): void => {}; + const attachStarted = new Promise((resolveStarted) => { + markAttachStarted = resolveStarted; + }); + let attached = false; + let mountPoint: string | undefined; + const host: NativeDmgHost = { + async run(arguments_, signal) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk21", + "mount-point": mountPoint, + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + mountPoint = join(mount.rememberRoot(arguments_), "Fixture"); + markAttachStarted(); + return new Promise((_, reject) => { + signal?.addEventListener( + "abort", + () => { + void mkdir(mountPoint ?? "").then(async () => { + attached = true; + await writeFile( + join(mountPoint ?? "", "hello.txt"), + "after exit", + ); + reject( + Object.assign(new Error("attach aborted"), { + name: "AbortError", + }), + ); + }); + }, + { once: true }, + ); + }); + }, + }; + + const creating = NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + controller.signal, + host, + ); + await attachStarted; + controller.abort(); + await expect(creating).rejects.toMatchObject({ reason: "cancelled" }); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + "detach", + ]); + expect(calls).toContainEqual(["detach", "/dev/disk21"]); + }); + + it("leaves a preexisting outside-root mount attached", async () => { + const calls: string[][] = []; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk22", + "mount-point": "/Volumes/AlreadyMounted", + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "attach") + return { + stdout: attachPlist([ + { + "dev-entry": "/dev/disk22", + "mount-point": "/Volumes/AlreadyMounted", + }, + ]), + exitCode: 0, + }; + return { stdout: "", exitCode: 0 }; + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ reason: "path" }); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([]); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + ]); }); }); describe("native DMG command failure diagnostics", () => { + it("removes an empty root when the attach process never started", async () => { + const calls: string[][] = []; + let mountRoot: string | undefined; + onTestFinished(async () => { + if (mountRoot !== undefined) + await rm(mountRoot, { recursive: true, force: true }); + }); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "verify") + return Promise.resolve({ stdout: "", exitCode: 0 }); + if (arguments_[0] === "info") + return Promise.resolve({ stdout: emptyInfoPlist, exitCode: 0 }); + if (arguments_[0] === "attach") { + mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; + return Promise.reject( + Object.assign(new Error("could not spawn hdiutil"), { + code: "ENOENT", + syscall: "spawn /usr/bin/hdiutil", + errno: -2, + }), + ); + } + throw new Error(`unexpected command: ${arguments_[0] ?? ""}`); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ + reason: "unavailable", + message: expect.stringContaining('"code":"ENOENT"'), + cleanup: undefined, + }); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + ]); + expect( + await realpath(mountRoot ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("native DMG command diagnostics", () => { it("keeps unknown attach failures unavailable with command evidence", async () => { await expect( NativeDmgArtifactReader.create("/tmp/image.dmg", process.env, undefined, { run(arguments_) { if (arguments_[0] === "verify") return Promise.resolve({ stdout: "", exitCode: 0 }); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); return Promise.resolve({ stdout: "attach output", stderr: "attach failed for an unknown reason", @@ -370,26 +912,43 @@ describe("native DMG real verification diagnostics", () => { it("owns the canonical mount root and detaches each observed whole image once", async () => { const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; const host: NativeDmgHost = { async run(arguments_) { calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { "dev-entry": "/dev/disk41" }, + { "dev-entry": "/dev/disk41s1" }, + { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk42" }, + { "dev-entry": "/dev/disk42s1" }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; - const mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - expect(mountRoot).toBe(await realpath(mountRoot)); - const mountPoint = join(await realpath(mountRoot), "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "hello"); + const mounted = await mount.createVolume(arguments_, "hello"); + expect(mounted.mountRoot).toBe(await realpath(mounted.mountRoot)); + mountPoint = mounted.mountPoint; + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk41" }, - { "dev-entry": "/dev/disk41s1" }, - { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, - { "dev-entry": "/dev/disk42" }, - { "dev-entry": "/dev/disk42s1" }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk41" }, + { "dev-entry": "/dev/disk41s1" }, + { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk42" }, + { "dev-entry": "/dev/disk42s1" }, + ]), exitCode: 0, }; }, @@ -421,11 +980,9 @@ const apfsHost = ( ) => { const calls: string[][] = []; let infoReads = 0; - let mountRoot: string | undefined; - onTestFinished(async () => { - if (mountRoot !== undefined) - await rm(mountRoot, { recursive: true, force: true }); - }); + const mount = createMountFixture(); + let mountPoint: string | undefined; + let attached = false; const host: NativeDmgHost = { delay: () => Promise.resolve(), async run(arguments_) { @@ -435,33 +992,48 @@ const apfsHost = ( if (arguments_[0] === "info") return { stdout: build({ - images: - stillListed.length === 0 || (infoReads += 1) > listedInfoReads - ? [] - : [ + images: !attached + ? [] + : infoReads++ === 0 + ? [ { - "system-entities": stillListed.map((device) => ({ - "dev-entry": device, - })), + "image-path": "/tmp/image.dmg", + "system-entities": [ + { "dev-entry": "/dev/disk4" }, + { "dev-entry": "/dev/disk4s1" }, + { + "dev-entry": "/dev/disk5s1", + ...(mountPoint === undefined + ? {} + : { "mount-point": mountPoint }), + }, + { "dev-entry": "/dev/disk5" }, + ], }, - ], + ] + : stillListed.length === 0 || infoReads > listedInfoReads + 1 + ? [] + : [ + { + "image-path": "/tmp/image.dmg", + "system-entities": stillListed.map((device) => ({ + "dev-entry": device, + })), + }, + ], }), exitCode: 0, }; if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; - mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - const mountPoint = join(mountRoot, "Fixture"); - await mkdir(mountPoint); + ({ mountPoint } = await mount.createVolume(arguments_)); + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk4" }, - { "dev-entry": "/dev/disk4s1" }, - { "dev-entry": "/dev/disk5s1", "mount-point": mountPoint }, - { "dev-entry": "/dev/disk5" }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk4" }, + { "dev-entry": "/dev/disk4s1" }, + { "dev-entry": "/dev/disk5s1", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk5" }, + ]), exitCode: 0, }; }, @@ -471,16 +1043,13 @@ const apfsHost = ( // One mounted device whose detach reports busy while `busy(attempt)` holds. const singleDeviceHost = (busy: (attempt: number) => boolean) => { + const mount = createMountFixture(); const state = { - attached: true, + attached: false, attempts: 0, mountRoot: undefined as string | undefined, waits: [] as number[], }; - onTestFinished(async () => { - if (state.mountRoot !== undefined) - await rm(state.mountRoot, { recursive: true, force: true }); - }); const host: NativeDmgHost = { delay: (milliseconds) => { state.waits.push(milliseconds); @@ -488,28 +1057,26 @@ const singleDeviceHost = (busy: (attempt: number) => boolean) => { }, async run(args) { if (args[0] === "attach") { - state.mountRoot = args[args.indexOf("-mountroot") + 1]; - if (state.mountRoot === undefined) - throw new Error("missing mount root"); - const mountPoint = join(state.mountRoot, "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "owned observation"); + const mounted = await mount.createVolume(args, "owned observation"); + state.mountRoot = mounted.mountRoot; + state.attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk7", "mount-point": mountPoint }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk7", "mount-point": mounted.mountPoint }, + ]), exitCode: 0, }; } if (args[0] === "info") return { - stdout: build({ - images: state.attached - ? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }] - : [], - }), + stdout: state.attached + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk7", + "mount-point": join(state.mountRoot ?? "", "Fixture"), + }, + ]) + : emptyInfoPlist, exitCode: 0, }; if (args[0] === "detach") { @@ -545,9 +1112,9 @@ const closeApfsFixture = async ( await reader.close(); return { reader, - cleanup: calls.filter( - (call) => call[0] !== "verify" && call[0] !== "attach", - ), + cleanup: calls + .slice(calls.findIndex((call) => call[0] === "attach") + 1) + .slice(1), }; }; From d83cbd2abf1bbf15beef990f5353457fdbaaeb8e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:35:15 +0800 Subject: [PATCH 017/189] test: share snapshot replay and managed graph fixtures --- .../mcp/workflowSnapshotReplayMcp.test.ts | 160 ++++--- .../managedApplicationGraph.test.ts | 97 ++--- .../directAnalysisSnapshotReplay.test.ts | 412 ++++++++---------- 3 files changed, 288 insertions(+), 381 deletions(-) diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts index 62369ca4d..1282aef36 100644 --- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts +++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts @@ -42,46 +42,27 @@ afterEach(async () => { describe("MCP composed workflow target admission", () => { it("keeps a composed result and snapshot on its admitted target across queued close and open", async () => { - const directory = await createTestTempDirectory( + const { targetPaths, snapshotPath } = await createWorkflowFiles( "rea-mcp-admitted-workflow-", + ["first.hop", "second.hop"], ); - const firstPath = join(directory, "first.hop"); - const secondPath = join(directory, "second.hop"); - const snapshotPath = join(directory, "first-analysis.json"); - await Promise.all([ - writeFile(firstPath, "first target"), - writeFile(secondPath, "second target"), - ]); + const firstPath = targetPaths[0]; + const secondPath = targetPaths[1]; + if (firstPath === undefined || secondPath === undefined) + throw new Error("Expected two workflow targets"); const starts: string[] = []; const calls: string[] = []; const entered = createDeferred(); const release = createDeferred(); - const session = createTestBinarySession( + const session = createWorkflowSession( makeProvider(starts, calls, undefined, { entered, release }), - { resolveAnalysisProfile: () => Promise.resolve(ok({ profile })) }, ); - const server = createServer( - { kind: "session", session }, - { logger: silentLogger }, - ); - const mcp = new Client({ name: "admitted-workflow", version: "1" }); + const { mcp } = await connectWorkflowMcp(session, "admitted-workflow"); const closeStarted = createDeferred(); mcp.setNotificationHandler("notifications/progress", () => { closeStarted.resolve(); }); - const [clientTransport, serverTransport] = - InMemoryTransport.createLinkedPair(); - resources.push(mcp, server); - await server.connect(serverTransport); - await mcp.connect(clientTransport); - expect( - ( - await mcp.callTool({ - name: "open_binary", - arguments: { path: firstPath }, - }) - ).isError, - ).not.toBe(true); + await openWorkflowTarget(mcp, firstPath); const analysisRequest = mcp.callTool({ name: "binary_overview", @@ -126,34 +107,19 @@ describe("MCP composed workflow target admission", () => { describe("MCP composed workflow snapshot replay", () => { it("exports an MCP workflow binding and replays its Evidence without provider startup or calls", async () => { - const directory = await createTestTempDirectory( + const { targetPaths, snapshotPath } = await createWorkflowFiles( "rea-mcp-workflow-snapshot-", + ["fixture.hop"], ); - const targetPath = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "analysis.json"); - await writeFile(targetPath, "fixture binary"); + const targetPath = targetPaths[0]; + if (targetPath === undefined) throw new Error("Expected a workflow target"); const starts: string[] = []; const calls: string[] = []; const provider = makeProvider(starts, calls); - const session = createTestBinarySession(provider, { - resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), - }); - const server = createServer( - { kind: "session", session }, - { logger: silentLogger }, - ); - const mcp = new Client({ name: "workflow-snapshot", version: "1.0.0" }); - const [clientTransport, serverTransport] = - InMemoryTransport.createLinkedPair(); - resources.push(mcp, server); - await server.connect(serverTransport); - await mcp.connect(clientTransport); + const session = createWorkflowSession(provider); + const { mcp } = await connectWorkflowMcp(session, "workflow-snapshot"); - const opened = await mcp.callTool({ - name: "open_binary", - arguments: { path: targetPath }, - }); - expect(opened.isError).not.toBe(true); + await openWorkflowTarget(mcp, targetPath); const analyzed = await mcp.callTool({ name: "binary_overview", arguments: {}, @@ -198,14 +164,8 @@ describe("MCP composed workflow snapshot replay", () => { const dependencies: DirectAnalysisDependencies = { readConfiguration: () => parseConfig({}), - createBinarySession: () => - createTestBinarySession(provider, { - resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), - }), - createManagedBinarySession: () => - createTestBinarySession(provider, { - resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), - }), + createBinarySession: () => createWorkflowSession(provider), + createManagedBinarySession: () => createWorkflowSession(provider), }; const replay = await runDirectAnalysis( dependencies, @@ -221,42 +181,20 @@ describe("MCP composed workflow snapshot replay", () => { }); it("does not bind a workflow when an upstream operation is live", async () => { - const directory = await createTestTempDirectory( + const { targetPaths, snapshotPath } = await createWorkflowFiles( "rea-mcp-live-workflow-snapshot-", + ["fixture.hop"], ); - const targetPath = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "analysis.json"); - await writeFile(targetPath, "fixture binary"); + const targetPath = targetPaths[0]; + if (targetPath === undefined) throw new Error("Expected a workflow target"); const starts: string[] = []; const calls: string[] = []; - const session = createTestBinarySession( + const session = createWorkflowSession( makeProvider(starts, calls, "list_strings"), - { - resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), - }, ); - const server = createServer( - { kind: "session", session }, - { logger: silentLogger }, - ); - const mcp = new Client({ - name: "live-workflow-snapshot", - version: "1.0.0", - }); - const [clientTransport, serverTransport] = - InMemoryTransport.createLinkedPair(); - resources.push(mcp, server); - await server.connect(serverTransport); - await mcp.connect(clientTransport); + const { mcp } = await connectWorkflowMcp(session, "live-workflow-snapshot"); - expect( - ( - await mcp.callTool({ - name: "open_binary", - arguments: { path: targetPath }, - }) - ).isError, - ).not.toBe(true); + await openWorkflowTarget(mcp, targetPath); const analyzed = await mcp.callTool({ name: "binary_overview", arguments: {}, @@ -279,6 +217,54 @@ describe("MCP composed workflow snapshot replay", () => { }); }); +const createWorkflowFiles = async ( + prefix: string, + filenames: readonly string[], +): Promise<{ + readonly targetPaths: readonly string[]; + readonly snapshotPath: string; +}> => { + const directory = await createTestTempDirectory(prefix); + const targetPaths = await Promise.all( + filenames.map(async (filename) => { + const path = join(directory, filename); + await writeFile(path, filename); + return path; + }), + ); + return { targetPaths, snapshotPath: join(directory, "analysis.json") }; +}; + +const createWorkflowSession = (provider: AnalysisProvider) => + createTestBinarySession(provider, { + resolveAnalysisProfile: () => Promise.resolve(ok({ profile })), + }); + +const connectWorkflowMcp = async ( + session: ReturnType, + clientName: string, +): Promise<{ readonly mcp: Client }> => { + const server = createServer( + { kind: "session", session }, + { logger: silentLogger }, + ); + const mcp = new Client({ name: clientName, version: "1.0.0" }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + resources.push(mcp, server); + await server.connect(serverTransport); + await mcp.connect(clientTransport); + return { mcp }; +}; + +const openWorkflowTarget = async (mcp: Client, path: string): Promise => { + const opened = await mcp.callTool({ + name: "open_binary", + arguments: { path }, + }); + expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true); +}; + const makeProvider = ( starts: string[], calls: string[], diff --git a/tests/composition/analysis-sessions/managedApplicationGraph.test.ts b/tests/composition/analysis-sessions/managedApplicationGraph.test.ts index 22eed0b21..e96efb442 100644 --- a/tests/composition/analysis-sessions/managedApplicationGraph.test.ts +++ b/tests/composition/analysis-sessions/managedApplicationGraph.test.ts @@ -233,72 +233,37 @@ describe("managed application graph coverage", () => { }); describe("managed application graph identity facts", () => { - it("uses member Evidence for its module and reports only emitted identity nodes", () => { - const bytes = buildManagedPeFixture(); - const binary = managedPeFixtureTarget(bytes, "/fixture/MembersOnly.dll"); - const members = inspectManagedMembersBytes(bytes, binary); - const aligned = createEvidence(binary, MANAGED_STATIC_PROVIDER, { - operation: "inspect_managed_members", - parameters: {}, - result: members, - }); - const projected = projectManagedApplicationGraphEvidence({ - managed_members: aligned, - }); - if (!projected.ok) throw projected.error; - const result = managedApplicationGraphResultSchema.parse( - parseEvidence(projected.value).normalized_result, - ); - const graph = parseJavaScriptApplicationGraph(result.graph); - expect(result.summary).toMatchObject({ assemblies: 0, modules: 1 }); - expect( - graph.nodes.find(({ kind }) => kind === "managed-module") - ?.observations[0], - ).toMatchObject({ - evidence: { - extractor: { operation: "inspect_managed_members" }, - evidence_ids: [aligned.evidence_id], - }, - }); - expect(result.evidence_links).toEqual([aligned.evidence_id]); - expect(result.limitations).toContain( - "Managed artifact Evidence was not supplied; assembly identity observations are absent.", - ); - }); - - it("binds a boundaries-only module node to the boundary Evidence that supplied it", () => { - const bytes = buildManagedPeFixture(); - const binary = managedPeFixtureTarget(bytes, "/fixture/BoundariesOnly.dll"); - const boundaries = inspectManagedNativeBoundariesBytes(bytes, binary); - const boundaryEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, { - operation: "inspect_managed_native_boundaries", - parameters: {}, - result: boundaries, - rawResult: null, - limitations: boundaries.limitations, - locations: [{ kind: "artifact-path", path: binary.path }], - }); - - const projected = projectManagedApplicationGraphEvidence({ - managed_native_boundaries: boundaryEvidence, - }); - if (!projected.ok) throw projected.error; - const result = managedApplicationGraphResultSchema.parse( - parseEvidence(projected.value).normalized_result, - ); - const graph = parseJavaScriptApplicationGraph(result.graph); - expect(result.summary).toMatchObject({ assemblies: 0, modules: 1 }); - expect( - graph.nodes.find(({ kind }) => kind === "managed-module") - ?.observations[0], - ).toMatchObject({ - evidence: { - extractor: { operation: "inspect_managed_native_boundaries" }, - evidence_ids: [boundaryEvidence.evidence_id], - }, - }); - expect(result.evidence_links).toEqual([boundaryEvidence.evidence_id]); - }); + it.each([ + ["managed_members", "memberEvidence"], + ["managed_native_boundaries", "boundaryEvidence"], + ] as const)( + "binds a module from %s to its supplying Evidence", + (inputKey, evidenceKey) => { + const source = createManagedInteropEvidence()[evidenceKey]; + const projected = projectManagedApplicationGraphEvidence({ + [inputKey]: source, + }); + if (!projected.ok) throw projected.error; + const result = managedApplicationGraphResultSchema.parse( + parseEvidence(projected.value).normalized_result, + ); + const graph = parseJavaScriptApplicationGraph(result.graph); + expect(result.summary).toMatchObject({ assemblies: 0, modules: 1 }); + expect( + graph.nodes.find(({ kind }) => kind === "managed-module") + ?.observations[0], + ).toMatchObject({ + evidence: { + extractor: { operation: source.operation }, + evidence_ids: [source.evidence_id], + }, + }); + expect(result.evidence_links).toEqual([source.evidence_id]); + expect(result.limitations).toContain( + "Managed artifact Evidence was not supplied; assembly identity observations are absent.", + ); + }, + ); it("reports no assembly or module when the inspector observes no identity rows", () => { const bytes = buildManagedPeFixture({ diff --git a/tests/composition/directAnalysisSnapshotReplay.test.ts b/tests/composition/directAnalysisSnapshotReplay.test.ts index 3fbf5d268..da6d3a11b 100644 --- a/tests/composition/directAnalysisSnapshotReplay.test.ts +++ b/tests/composition/directAnalysisSnapshotReplay.test.ts @@ -118,14 +118,26 @@ const expectWorkflowQuestionsRetained = ( ); }; +interface SnapshotProviderTrace { + readonly starts: string[]; + readonly calls: string[]; + readonly resolutions: string[]; +} + +interface SnapshotProviderOptions { + readonly profile?: ReturnType; + readonly identity?: ProviderIdentity; + readonly supportedOperations?: readonly CapabilityDescriptor["operation"][]; +} + const makeProvider = ( - starts: string[], - calls: string[], - profile = createAnalysisProfile(IDENTITY, { fixture: true }), - identity: ProviderIdentity = profile.provider, - supportedOperations: readonly CapabilityDescriptor["operation"][] = operations, - resolutions: string[] = [], + trace: SnapshotProviderTrace, + options: SnapshotProviderOptions = {}, ): AnalysisProvider => { + const profile = + options.profile ?? createAnalysisProfile(IDENTITY, { fixture: true }); + const identity = options.identity ?? profile.provider; + const supportedOperations = options.supportedOperations ?? operations; const capabilities: CapabilityDescriptor[] = supportedOperations.map( (operation) => ({ operation, @@ -149,14 +161,14 @@ const makeProvider = ( identity: () => identity, capabilities: () => capabilities, resolveAnalysisProfile: async () => { - resolutions.push(profile.digest); + trace.resolutions.push(profile.digest); return ok({ profile }); }, createClient: () => { - starts.push("start"); + trace.starts.push("start"); return { execute: async (operation) => { - calls.push(operation); + trace.calls.push(operation); const results: Readonly> = { health: null, list_segments: [{ name: "__TEXT", start: "0x1000", end: "0x2000" }], @@ -189,6 +201,37 @@ const makeProvider = ( }; }; +const createSnapshotReplayFixture = async ( + directoryPrefix: string, + snapshotRelativePath = "snapshot.json", +) => { + const directory = await createTestTempDirectory(directoryPrefix); + const path = join(directory, "fixture.hop"); + const snapshotPath = join(directory, snapshotRelativePath); + await writeFile(path, "fixture"); + const starts: string[] = []; + const calls: string[] = []; + const resolutions: string[] = []; + + return { + path, + snapshotPath, + starts, + calls, + resolutions, + createProvider(options: SnapshotProviderOptions = {}): AnalysisProvider { + return makeProvider({ starts, calls, resolutions }, options); + }, + dependencies(provider: AnalysisProvider): DirectAnalysisDependencies { + return { + readConfiguration: () => parseConfig({}), + createBinarySession: () => createTestBinarySession(provider), + createManagedBinarySession: () => createTestBinarySession(provider), + }; + }, + }; +}; + const withAlternateWorkflowProfile = ( snapshot: AnalysisSnapshot, path: string, @@ -295,61 +338,48 @@ describe("direct analysis composed snapshot replay", () => { ] as const)( "reuses the previewed profile on a $tool snapshot miss", async (scenario) => { - const directory = await createTestTempDirectory( + const fixture = await createSnapshotReplayFixture( "rea-snapshot-miss-route-", ); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const resolutions: string[] = []; const profile = createAnalysisProfile(IDENTITY, { fixture: true }); - const provider = makeProvider( - starts, - calls, + const provider = fixture.createProvider({ profile, - IDENTITY, - workflowProviderOperations, - resolutions, - ); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + identity: IDENTITY, + supportedOperations: workflowProviderOperations, + }); + const dependencies = fixture.dependencies(provider); await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - expect(resolutions).toHaveLength(1); + expect(fixture.resolutions).toHaveLength(1); const first = await runDirectAnalysis( dependencies, - path, + fixture.path, scenario.tool, scenario.arguments, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(first).toMatchObject({ operation: scenario.tool }); - expect(resolutions).toHaveLength(2); - expect(starts).toHaveLength(2); - const callsAfterMiss = [...calls]; + expect(fixture.resolutions).toHaveLength(2); + expect(fixture.starts).toHaveLength(2); + const callsAfterMiss = [...fixture.calls]; const replay = await runDirectAnalysis( dependencies, - path, + fixture.path, scenario.tool, scenario.arguments, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(replay).toEqual(first); - expect(resolutions).toHaveLength(3); - expect(starts).toHaveLength(2); - expect(calls).toEqual(callsAfterMiss); + expect(fixture.resolutions).toHaveLength(3); + expect(fixture.starts).toHaveLength(2); + expect(fixture.calls).toEqual(callsAfterMiss); }, ); @@ -372,34 +402,24 @@ describe("direct analysis composed snapshot replay", () => { }, ] as const) { it(`persists and replays ${scenario.tool} without provider startup`, async () => { - const directory = await createTestTempDirectory("rea-workflow-command-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const provider = makeProvider( - starts, - calls, - createAnalysisProfile(IDENTITY, { fixture: true }), - IDENTITY, - workflowProviderOperations, + const fixture = await createSnapshotReplayFixture( + "rea-workflow-command-", ); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const provider = fixture.createProvider({ + identity: IDENTITY, + supportedOperations: workflowProviderOperations, + }); + const dependencies = fixture.dependencies(provider); const first = await runDirectAnalysis( dependencies, - path, + fixture.path, scenario.tool, scenario.arguments, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - const callsAfterFirst = [...calls]; - const startsAfterFirst = [...starts]; - const loaded = await readAnalysisSnapshot(snapshotPath); + const callsAfterFirst = [...fixture.calls]; + const startsAfterFirst = [...fixture.starts]; + const loaded = await readAnalysisSnapshot(fixture.snapshotPath); if (!loaded.ok) throw loaded.error; expect( loaded.value.workflow_entries.map(({ operation }) => operation), @@ -409,15 +429,15 @@ describe("direct analysis composed snapshot replay", () => { const second = await runDirectAnalysis( dependencies, - path, + fixture.path, scenario.tool, scenario.arguments, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(second).toEqual(first); - expect(calls).toEqual(callsAfterFirst); - expect(starts).toEqual(startsAfterFirst); + expect(fixture.calls).toEqual(callsAfterFirst); + expect(fixture.starts).toEqual(startsAfterFirst); }); } }); @@ -430,80 +450,65 @@ describe("Ghidra composed workflow snapshot replay", () => { ] as const)( "persists and replays $tool with production Ghidra capability policies", async ({ tool, arguments: parameters }) => { - const directory = await createTestTempDirectory("rea-ghidra-workflow-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; + const fixture = await createSnapshotReplayFixture("rea-ghidra-workflow-"); const profile = createAnalysisProfile( { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" }, { fixture: true }, ); const provider: AnalysisProvider = { - ...makeProvider(starts, calls, profile, GHIDRA_PROVIDER_IDENTITY), + ...fixture.createProvider({ + profile, + identity: GHIDRA_PROVIDER_IDENTITY, + }), capabilities: () => GHIDRA_CAPABILITIES, }; - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const dependencies = fixture.dependencies(provider); const first = await runDirectAnalysis( dependencies, - path, + fixture.path, tool, parameters, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(first).toMatchObject({ operation: tool }); - const snapshot = await readAnalysisSnapshot(snapshotPath); + const snapshot = await readAnalysisSnapshot(fixture.snapshotPath); if (!snapshot.ok) throw snapshot.error; expect(snapshot.value.workflow_entries).toEqual([ expect.objectContaining({ operation: tool }), ]); - const initialCalls = [...calls]; + const initialCalls = [...fixture.calls]; const replay = await runDirectAnalysis( dependencies, - path, + fixture.path, tool, parameters, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(replay).toEqual(first); - expect(starts).toHaveLength(1); - expect(calls).toEqual(initialCalls); + expect(fixture.starts).toHaveLength(1); + expect(fixture.calls).toEqual(initialCalls); }, ); }); describe("binary overview snapshot replay", () => { it("replays the identical binary overview without provider startup or calls", async () => { - const directory = await createTestTempDirectory("rea-workflow-snapshot-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const provider = makeProvider(starts, calls); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const fixture = await createSnapshotReplayFixture("rea-workflow-snapshot-"); + const provider = fixture.createProvider(); + const dependencies = fixture.dependencies(provider); const first = await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - expect(calls.toSorted()).toEqual(operations.toSorted()); - expect(starts).toHaveLength(1); + expect(fixture.calls.toSorted()).toEqual(operations.toSorted()); + expect(fixture.starts).toHaveLength(1); - const loaded = await readAnalysisSnapshot(snapshotPath); + const loaded = await readAnalysisSnapshot(fixture.snapshotPath); if (!loaded.ok) throw loaded.error; expect(loaded.value.workflow_entries).toHaveLength(1); const current = loaded.value.evidence_bundle.records.find( @@ -514,8 +519,8 @@ describe("binary overview snapshot replay", () => { expect( ( await writeAnalysisSnapshot( - withEarlierHistoricalEvidence(loaded.value, path, current), - snapshotPath, + withEarlierHistoricalEvidence(loaded.value, fixture.path, current), + fixture.snapshotPath, true, ) ).ok, @@ -523,52 +528,41 @@ describe("binary overview snapshot replay", () => { const second = await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(second).toEqual(first); - expect(calls.toSorted()).toEqual(operations.toSorted()); - expect(starts).toHaveLength(1); + expect(fixture.calls.toSorted()).toEqual(operations.toSorted()); + expect(fixture.starts).toHaveLength(1); }); }); describe("snapshot replay provider identity", () => { it("uses the resolved provider version when capability metadata omits it", async () => { - const directory = await createTestTempDirectory("rea-profile-version-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; + const fixture = await createSnapshotReplayFixture("rea-profile-version-"); const unresolvedIdentity = { ...IDENTITY, version: null }; const resolvedProfile = createAnalysisProfile( { ...IDENTITY, version: "launcher-sha256:fixture" }, { fixture: true }, ); - const provider = makeProvider( - starts, - calls, - resolvedProfile, - unresolvedIdentity, - ["search_strings"], - ); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const provider = fixture.createProvider({ + profile: resolvedProfile, + identity: unresolvedIdentity, + supportedOperations: ["search_strings"], + }); + const dependencies = fixture.dependencies(provider); const first = await runDirectAnalysis( dependencies, - path, + fixture.path, "search_strings", { pattern: "fixture", document: "fixture" }, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - const callsAfterFirst = [...calls]; - const startsAfterFirst = [...starts]; - const firstSnapshot = await readAnalysisSnapshot(snapshotPath); + const callsAfterFirst = [...fixture.calls]; + const startsAfterFirst = [...fixture.starts]; + const firstSnapshot = await readAnalysisSnapshot(fixture.snapshotPath); if (!firstSnapshot.ok) throw firstSnapshot.error; expect(firstSnapshot.value.entries[0]?.execution.provider.version).toBe( "launcher-sha256:fixture", @@ -576,101 +570,80 @@ describe("snapshot replay provider identity", () => { const second = await runDirectAnalysis( dependencies, - path, + fixture.path, "search_strings", { pattern: "fixture", document: "fixture" }, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - expect(calls).toEqual(callsAfterFirst); - expect(starts).toEqual(startsAfterFirst); + expect(fixture.calls).toEqual(callsAfterFirst); + expect(fixture.starts).toEqual(startsAfterFirst); expect(second).toEqual(first); - const changedProfileProvider = makeProvider( - starts, - calls, - createAnalysisProfile( + const changedProfileProvider = fixture.createProvider({ + profile: createAnalysisProfile( { ...IDENTITY, version: "launcher-sha256:changed" }, { fixture: true }, ), - unresolvedIdentity, - ["search_strings"], - ); + identity: unresolvedIdentity, + supportedOperations: ["search_strings"], + }); const changedProfileResult = await runDirectAnalysis( - { - readConfiguration: () => parseConfig({}), - createBinarySession: () => - createTestBinarySession(changedProfileProvider), - createManagedBinarySession: () => - createTestBinarySession(changedProfileProvider), - }, - path, + fixture.dependencies(changedProfileProvider), + fixture.path, "search_strings", { pattern: "fixture", document: "fixture" }, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(changedProfileResult).not.toEqual(first); expect(changedProfileResult).toMatchObject({ code: "evidence_integrity_mismatch", }); - expect(starts).toEqual(startsAfterFirst); - expect(calls).toEqual(callsAfterFirst); + expect(fixture.starts).toEqual(startsAfterFirst); + expect(fixture.calls).toEqual(callsAfterFirst); const changedProviderIdentity = { id: "other-provider", name: "Other Provider", version: null, }; - const changedProvider = makeProvider( - starts, - calls, - createAnalysisProfile( + const changedProvider = fixture.createProvider({ + profile: createAnalysisProfile( { ...changedProviderIdentity, version: "other-version" }, { fixture: true }, ), - changedProviderIdentity, - ["search_strings"], - ); + identity: changedProviderIdentity, + supportedOperations: ["search_strings"], + }); const changedProviderResult = await runDirectAnalysis( - { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(changedProvider), - createManagedBinarySession: () => - createTestBinarySession(changedProvider), - }, - path, + fixture.dependencies(changedProvider), + fixture.path, "search_strings", { pattern: "fixture", document: "fixture" }, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(changedProviderResult).not.toEqual(first); expect(changedProviderResult).toMatchObject({ code: "evidence_integrity_mismatch", }); - expect(starts).toEqual(startsAfterFirst); - expect(calls).toEqual(callsAfterFirst); + expect(fixture.starts).toEqual(startsAfterFirst); + expect(fixture.calls).toEqual(callsAfterFirst); }); }); const assertEvidenceSurvivesSnapshotSaveFailure = async (): Promise => { - const directory = await createTestTempDirectory("rea-workflow-save-error-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "missing", "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const provider = makeProvider(starts, calls); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const fixture = await createSnapshotReplayFixture( + "rea-workflow-save-error-", + join("missing", "snapshot.json"), + ); + const provider = fixture.createProvider(); + const dependencies = fixture.dependencies(provider); const result = await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(result).toMatchObject({ @@ -678,7 +651,7 @@ const assertEvidenceSurvivesSnapshotSaveFailure = async (): Promise => { details: { partial_observation: { operation: "binary_overview", - subject: { local_path: path }, + subject: { local_path: fixture.path }, }, }, }); @@ -688,7 +661,7 @@ const assertEvidenceSurvivesSnapshotSaveFailure = async (): Promise => { }) .parse(result).details.partial_observation; expect(parseEvidence(partial).operation).toBe("binary_overview"); - expect(calls.toSorted()).toEqual(operations.toSorted()); + expect(fixture.calls.toSorted()).toEqual(operations.toSorted()); }; describe("workflow snapshot profile and cancellation binding", () => { @@ -697,26 +670,17 @@ describe("workflow snapshot profile and cancellation binding", () => { assertEvidenceSurvivesSnapshotSaveFailure, ); it("does not replay a valid entry from a different workflow profile", async () => { - const directory = await createTestTempDirectory("rea-workflow-profile-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const provider = makeProvider(starts, calls); - const dependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const fixture = await createSnapshotReplayFixture("rea-workflow-profile-"); + const provider = fixture.createProvider(); + const dependencies = fixture.dependencies(provider); await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); - const loaded = await readAnalysisSnapshot(snapshotPath); + const loaded = await readAnalysisSnapshot(fixture.snapshotPath); if (!loaded.ok) throw loaded.error; const current = loaded.value.evidence_bundle.records.find( (record) => record.operation === "binary_overview", @@ -726,8 +690,8 @@ describe("workflow snapshot profile and cancellation binding", () => { expect( ( await writeAnalysisSnapshot( - withAlternateWorkflowProfile(loaded.value, path, current), - snapshotPath, + withAlternateWorkflowProfile(loaded.value, fixture.path, current), + fixture.snapshotPath, true, ) ).ok, @@ -735,38 +699,30 @@ describe("workflow snapshot profile and cancellation binding", () => { const refreshed = await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); expect(refreshed).toMatchObject({ normalized_result: { document: "fixture" }, }); - expect(calls.toSorted()).toEqual([...operations, ...operations].toSorted()); - expect(starts).toHaveLength(2); + expect(fixture.calls.toSorted()).toEqual( + [...operations, ...operations].toSorted(), + ); + expect(fixture.starts).toHaveLength(2); }); it("does not return a cached result when cancelled during route resolution", async () => { - const directory = await createTestTempDirectory("rea-workflow-cancel-"); - const path = join(directory, "fixture.hop"); - const snapshotPath = join(directory, "snapshot.json"); - await writeFile(path, "fixture"); - const starts: string[] = []; - const calls: string[] = []; - const profile = createAnalysisProfile(IDENTITY, { fixture: true }); - const provider = makeProvider(starts, calls, profile); - const initialDependencies: DirectAnalysisDependencies = { - readConfiguration: () => parseConfig({}), - createBinarySession: () => createTestBinarySession(provider), - createManagedBinarySession: () => createTestBinarySession(provider), - }; + const fixture = await createSnapshotReplayFixture("rea-workflow-cancel-"); + const provider = fixture.createProvider(); + const initialDependencies = fixture.dependencies(provider); await runDirectAnalysis( initialDependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath }, + { snapshotPath: fixture.snapshotPath }, ); const controller = new AbortController(); @@ -785,17 +741,17 @@ describe("workflow snapshot profile and cancellation binding", () => { }; const result = await runDirectAnalysis( dependencies, - path, + fixture.path, "binary_overview", {}, - { snapshotPath, signal: controller.signal }, + { snapshotPath: fixture.snapshotPath, signal: controller.signal }, ); expect(result).toMatchObject({ error: "Analysis failed", code: "cancelled", }); - expect(calls.toSorted()).toEqual(operations.toSorted()); - expect(starts).toHaveLength(1); + expect(fixture.calls.toSorted()).toEqual(operations.toSorted()); + expect(fixture.starts).toHaveLength(1); }); }); From 56598beb4e82968a313deb9efdf4b98db5bd1f4f Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:40:45 -0700 Subject: [PATCH 018/189] perf(json): encode streamed JSON iteratively (#1322) The streamed JSON encoder delegated every token through one recursive generator per nesting level and yielded each token separately. Writing analyze-javascript-application output for Typora (873 MB) spent 22 of 66 s there. Encode with an explicit stack into bounded 16 KiB parts: identical bytes, 3-6x faster encoding, and the same laziness, error and surrogate-pair guarantees. Co-authored-by: Claude Opus 5.5 --- src/domain/jsonSerialization.test.ts | 71 ++++++++-- src/domain/jsonSerialization.ts | 190 ++++++++++++++++++--------- 2 files changed, 193 insertions(+), 68 deletions(-) diff --git a/src/domain/jsonSerialization.test.ts b/src/domain/jsonSerialization.test.ts index bca145a95..45caf7898 100644 --- a/src/domain/jsonSerialization.test.ts +++ b/src/domain/jsonSerialization.test.ts @@ -7,6 +7,16 @@ import { jsonParts, } from "./jsonSerialization.js"; +/** Compact and pretty streamed JSON must equal native JSON. */ +const expectNativeJson = (value: unknown): void => { + expect([...bufferedJsonParts(jsonParts(value))].join("")).toBe( + JSON.stringify(value), + ); + expect([...jsonParts(value, true)].join("")).toBe( + JSON.stringify(value, null, 2), + ); +}; + describe("streamed JSON representation", () => { it.each([ null, @@ -15,14 +25,7 @@ describe("streamed JSON representation", () => { [1, false, null, 'quotes: " / slash: \\ / newline: \n'], { nested: { value: "中文 😀 \ud800" }, items: [1, 2] }, JSON.parse('{"__proto__":{"value":1},"constructor":2,"10":3,"2":4}'), - ])("matches native JSON for ordinary values: %j", (value: unknown) => { - expect([...bufferedJsonParts(jsonParts(value))].join("")).toBe( - JSON.stringify(value), - ); - expect([...jsonParts(value, true)].join("")).toBe( - JSON.stringify(value, null, 2), - ); - }); + ])("matches native JSON for ordinary values: %j", expectNativeJson); it("preserves surrogate pairs across string and buffer boundaries", () => { const value = { text: `${"x".repeat(8190)}😀${'中文\n"'.repeat(20000)}` }; @@ -59,3 +62,55 @@ describe("streamed JSON representation", () => { ); }); }); + +describe("iterative JSON encoding", () => { + it("matches native JSON for long keys, omitted members, and deep nesting", () => { + let deep: unknown = { leaf: [1, "two", null] }; + for (let level = 0; level < 500; level += 1) + deep = level % 2 === 0 ? [deep, level] : { [`k${String(level)}`]: deep }; + const value = { + [`${"k".repeat(9000)}😀`]: { nested: ["x".repeat(20000), {}, []] }, + omitted: undefined, + method: () => 1, + symbol: Symbol("ignored"), + deep, + }; + expectNativeJson(value); + }); + + it("rejects values native JSON would not encode as ordinary JSON", () => { + expect(() => [...jsonParts([1, undefined])]).toThrow( + "ordinary JSON values", + ); + expect(() => [...jsonParts({ value: Number.NaN })]).toThrow( + "ordinary JSON values", + ); + expect(() => [...jsonParts({ value: new Date(0) })]).toThrow( + "ordinary JSON objects", + ); + }); + + it("yields bounded parts before reading later members", () => { + const value: Record = { first: "x".repeat(100_000) }; + Object.defineProperty(value, "later", { + enumerable: true, + get() { + throw new Error("later members must not be read yet"); + }, + }); + const parts = jsonParts(value); + const first = parts.next(); + expect(first.done).toBe(false); + expect(first.value?.length).toBeLessThanOrEqual(64 * 1024); + // Many small members are grouped into parts instead of one per token. + const small = Object.fromEntries( + Array.from({ length: 10_000 }, (_, index) => [ + `k${String(index)}`, + index, + ]), + ); + const smallParts = [...jsonParts(small)]; + expect(smallParts.join("")).toBe(JSON.stringify(small)); + expect(smallParts.length).toBeLessThan(20); + }); +}); diff --git a/src/domain/jsonSerialization.ts b/src/domain/jsonSerialization.ts index 57462f254..65330950e 100644 --- a/src/domain/jsonSerialization.ts +++ b/src/domain/jsonSerialization.ts @@ -1,11 +1,11 @@ /** Encode ordinary JSON as bounded string parts without a document-sized allocation. */ export function* jsonParts(value: unknown, pretty = false): Generator { - yield* encodeValue(value, pretty, 0, new Set(), false); + yield* encodeValue(value, pretty, false); } /** Encode validated JSON with canonical key ordering without allocating the whole document. */ export function* canonicalJsonParts(value: unknown): Generator { - yield* encodeValue(value, false, 0, new Set(), true); + yield* encodeValue(value, false, true); } /** Buffer JSON parts while preserving complete UTF-16 surrogate pairs. */ @@ -46,73 +46,143 @@ function* encodeString(value: string): Generator { yield '"'; } -function* encodeValue( +/** Encoded text accumulated before it is yielded as one part. */ +const PART_CHARACTERS = 16 * 1024; + +const indentation: string[] = []; +const indent = (depth: number): string => + (indentation[depth] ??= `\n${" ".repeat(depth)}`); + +interface ContainerFrame { + readonly value: object; + readonly array: boolean; + readonly keys: readonly string[] | undefined; + readonly count: number; + readonly depth: number; + index: number; + written: number; +} + +/** Encoded text of a scalar, or undefined for a container or a long string. */ +const scalarText = (value: unknown): string | undefined => { + if (typeof value === "string") + return value.length <= 8192 ? JSON.stringify(value) : undefined; + if (value === null) return "null"; + if (typeof value === "boolean") return String(value); + if (typeof value === "number" && Number.isFinite(value)) return String(value); + return undefined; +}; + +const openContainer = ( value: unknown, - pretty: boolean, depth: number, ancestors: Set, canonical: boolean, -): Generator { - if (typeof value === "string") { - yield* encodeString(value); - return; - } - if (value === null || typeof value === "boolean") { - yield value === null ? "null" : String(value); - return; - } - if (typeof value === "number" && Number.isFinite(value)) { - yield String(value); - return; - } +): ContainerFrame => { if (typeof value !== "object" || value === null) throw new TypeError("JSON output requires ordinary JSON values"); if (ancestors.has(value)) throw new TypeError("JSON output contains a circular reference"); - if ( - !Array.isArray(value) && - Object.prototype.toString.call(value) !== "[object Object]" - ) + const array = Array.isArray(value); + if (!array && Object.prototype.toString.call(value) !== "[object Object]") throw new TypeError("JSON output requires ordinary JSON objects"); ancestors.add(value); - try { - const array = Array.isArray(value); - const keys = array ? undefined : Object.keys(value); - if (canonical) keys?.sort(); - const count = array ? value.length : (keys?.length ?? 0); - let written = 0; - yield array ? "[" : "{"; - for (let index = 0; index < count; index += 1) { - let item: unknown; - let key: string | undefined; - if (array) { - item = value[index]; - } else { - key = keys?.[index]; - if (key === undefined) - throw new TypeError("JSON object changed during serialization"); - item = Reflect.get(value, key); - // Incur's filter can select inherited methods. Match native JSON's - // omission without eagerly reading the rest of a bounded result. - if ( - item === undefined || - typeof item === "function" || - typeof item === "symbol" - ) - continue; - } - if (written > 0) yield ","; - if (pretty) yield `\n${" ".repeat(depth + 1)}`; - if (key !== undefined) { - yield* encodeString(key); - yield pretty ? ": " : ":"; - } - yield* encodeValue(item, pretty, depth + 1, ancestors, canonical); - written += 1; - } - if (pretty && written > 0) yield `\n${" ".repeat(depth)}`; - yield array ? "]" : "}"; - } finally { - ancestors.delete(value); + const keys = array ? undefined : Object.keys(value); + if (canonical) keys?.sort(); + const count = array ? value.length : (keys?.length ?? 0); + return { value, array, keys, count, depth, index: 0, written: 0 }; +}; + +/** The next written member of a container, skipping values JSON omits. */ +const nextMember = ( + frame: ContainerFrame, +): { readonly key: string | undefined; readonly item: unknown } | undefined => { + while (frame.index < frame.count) { + const index = frame.index; + frame.index += 1; + if (frame.array) + return { key: undefined, item: Reflect.get(frame.value, index) }; + const key = frame.keys?.[index]; + if (key === undefined) + throw new TypeError("JSON object changed during serialization"); + const item: unknown = Reflect.get(frame.value, key); + // Incur's filter can select inherited methods. Match native JSON's + // omission without eagerly reading the rest of a bounded result. + if ( + item !== undefined && + typeof item !== "function" && + typeof item !== "symbol" + ) + return { key, item }; } + return undefined; +}; + +/** + * Encode iteratively into bounded parts. Recursive `yield*` delegation passed + * every token through one generator frame per nesting level, which dominated + * the cost of writing large nested results. + */ +function* encodeValue( + root: unknown, + pretty: boolean, + canonical: boolean, +): Generator { + const ancestors = new Set(); + const stack: ContainerFrame[] = []; + let buffer = ""; + let pending: unknown = root; + let hasPending = true; + while (true) { + if (hasPending) { + hasPending = false; + const text = scalarText(pending); + if (text !== undefined) buffer += text; + else if (typeof pending === "string") { + // A long string is split into surrogate-safe parts of its own. + if (buffer !== "") yield buffer; + buffer = ""; + yield* encodeString(pending); + } else { + const frame = openContainer( + pending, + stack.length, + ancestors, + canonical, + ); + stack.push(frame); + buffer += frame.array ? "[" : "{"; + } + } + if (buffer.length >= PART_CHARACTERS) { + yield buffer; + buffer = ""; + } + const frame = stack.at(-1); + if (frame === undefined) break; + const member = nextMember(frame); + if (member === undefined) { + if (pretty && frame.written > 0) buffer += indent(frame.depth); + buffer += frame.array ? "]" : "}"; + ancestors.delete(frame.value); + stack.pop(); + continue; + } + if (frame.written > 0) buffer += ","; + if (pretty) buffer += indent(frame.depth + 1); + if (member.key !== undefined) { + const key = scalarText(member.key); + if (key !== undefined) buffer += key; + else { + if (buffer !== "") yield buffer; + buffer = ""; + yield* encodeString(member.key); + } + buffer += pretty ? ": " : ":"; + } + frame.written += 1; + pending = member.item; + hasPending = true; + } + if (buffer !== "") yield buffer; } From 1b73b5ab4bc75bd424e643de8e49f142ffa2b336 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:41:03 -0700 Subject: [PATCH 019/189] fix(native): refuse to list architectures of non-Mach-O targets (#1325) list_architectures ran lipo on every admitted target. For a PE DLL, ELF binary or plist, lipo's refusal surfaced as execution_failure with "Retry once; if it continues, run rea doctor", which neither can fix. Refuse non-Mach-O targets as capability_unavailable before running lipo, as inspect_macho already does. Co-authored-by: Claude Opus 5.5 --- src/native/NativeMacOSProvider.ts | 10 ++++++++ .../providers/native/nativeProvider.test.ts | 25 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index c73cd7605..0d25f969c 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -283,6 +283,16 @@ class NativeMacOSClient implements AnalysisClient { async #listArchitectures( signal?: AbortSignal, ): Promise> { + // lipo reads only Mach-O; its refusal of a PE, ELF, or plist target is not + // a tool failure that a retry or `rea doctor` could repair. + if (this.target.format !== "mach-o") + return err( + new AnalysisCapabilityUnavailableError( + IDENTITY.id, + "list_architectures", + "Active artifact is not Mach-O.", + ), + ); const capture = await this.#run( "list_architectures", "lipo", diff --git a/tests/boundary/providers/native/nativeProvider.test.ts b/tests/boundary/providers/native/nativeProvider.test.ts index 7653d871c..d5be920ba 100644 --- a/tests/boundary/providers/native/nativeProvider.test.ts +++ b/tests/boundary/providers/native/nativeProvider.test.ts @@ -694,6 +694,31 @@ describe("native macOS provider failures and parsing", () => { } }); + it.each([ + { + ...machoTarget("/fixture.dll"), + format: "pe" as const, + executableRole: "shared-library" as const, + managed: false, + }, + { ...machoTarget("/fixture.elf"), format: "elf" as const }, + ])( + "refuses to list architectures of a $format target without running lipo", + async (target) => { + const runner = new CountingRunner(); + const result = await new NativeMacOSProvider({}, runner, "darwin") + .createClient(target) + .execute("list_architectures", {}); + if (result.ok) throw new Error("Expected a non-Mach-O refusal"); + expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "capability_unavailable", + details: { reason: "Active artifact is not Mach-O." }, + }); + expect(runner.calls).toBe(0); + }, + ); + it("classifies pre-aborted requests before operation or runner discovery", async () => { const controller = new AbortController(); controller.abort(); From 5ecc98a5eac4c10d33e9c418b9ffae61c68e3ef2 Mon Sep 17 00:00:00 2001 From: N0zoM1z0 <1705004398@qq.com> Date: Fri, 9 Oct 2026 16:43:35 +0000 Subject: [PATCH 020/189] =?UTF-8?q?docs:=20celebrate=2040,000=20GitHub=20s?= =?UTF-8?q?tars=20=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- README_ar.md | 2 +- README_de.md | 2 +- README_es.md | 2 +- README_fa.md | 2 +- README_fr.md | 2 +- README_ja.md | 2 +- README_ko.md | 2 +- README_pl.md | 2 +- README_pt-BR.md | 2 +- README_ru.md | 2 +- README_th.md | 2 +- README_tr.md | 2 +- README_uk.md | 2 +- README_vi.md | 2 +- README_zh-TW.md | 2 +- README_zh.md | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 3475d8155..8c25a3ff5 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,7 @@ Report vulnerabilities through [SECURITY.md](SECURITY.md). ## Star history -🎉 **30,000 GitHub stars — thank you!** +🎉 **40,000 GitHub stars — thank you!** Thanks to everyone using REA, reporting bugs, requesting features, testing builds, and contributing fixes. diff --git a/README_ar.md b/README_ar.md index f4dcbda85..c2421439b 100644 --- a/README_ar.md +++ b/README_ar.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## سجل النجوم -🎉 **30,000 نجمة على GitHub — شكرًا لكم!** +🎉 **40,000 نجمة على GitHub — شكرًا لكم!** شكرًا لكل من يستخدم REA، ويبلّغ عن الأخطاء، ويقترح ميزات، ويختبر إصدارات البناء، ويساهم بالإصلاحات. diff --git a/README_de.md b/README_de.md index 6e74d0cba..de83b78a5 100644 --- a/README_de.md +++ b/README_de.md @@ -256,7 +256,7 @@ Melde Sicherheitslücken gemäß [SECURITY.md](SECURITY.md). ## Sternverlauf -🎉 **30.000 GitHub-Sterne – vielen Dank!** +🎉 **40.000 GitHub-Sterne – vielen Dank!** Danke an alle, die REA nutzen, Fehler melden, Funktionswünsche äußern, Builds testen und Fehlerbehebungen beitragen. diff --git a/README_es.md b/README_es.md index db73301c1..54cbcbf0d 100644 --- a/README_es.md +++ b/README_es.md @@ -256,7 +256,7 @@ Informa de vulnerabilidades siguiendo [SECURITY.md](SECURITY.md). ## Historial de estrellas -🎉 **30.000 estrellas en GitHub: ¡gracias!** +🎉 **40.000 estrellas en GitHub: ¡gracias!** Gracias a quienes usan REA, informan de errores, solicitan funciones, prueban compilaciones y contribuyen con correcciones. diff --git a/README_fa.md b/README_fa.md index fbf8bc086..1fe6e6df6 100644 --- a/README_fa.md +++ b/README_fa.md @@ -241,7 +241,7 @@ npx rea-agents@latest setup ## تاریخچهٔ ستاره‌ها -🎉 **۳۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** +🎉 **۴۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** از همهٔ کسانی که از REA استفاده می‌کنند، خطاها را گزارش می‌دهند، قابلیت‌های جدید پیشنهاد می‌کنند، buildها را آزمایش می‌کنند و در بهبود پروژه مشارکت دارند سپاسگزاریم. diff --git a/README_fr.md b/README_fr.md index 0b01db697..d61d3198c 100644 --- a/README_fr.md +++ b/README_fr.md @@ -257,7 +257,7 @@ Signalez les vulnérabilités via [SECURITY.md](SECURITY.md). ## Historique des étoiles -🎉 **30 000 étoiles GitHub — merci !** +🎉 **40 000 étoiles GitHub — merci !** Merci à toutes les personnes qui utilisent REA, signalent des bugs, proposent des fonctionnalités, testent les builds et contribuent des correctifs. diff --git a/README_ja.md b/README_ja.md index 2bdb5eb23..ba30700f6 100644 --- a/README_ja.md +++ b/README_ja.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## スター履歴 -🎉 **GitHub スター 30,000 件、ありがとうございます!** +🎉 **GitHub スター 40,000 件、ありがとうございます!** REA の利用、バグ報告、機能の要望、ビルドのテスト、修正への貢献に感謝します。 diff --git a/README_ko.md b/README_ko.md index 9ce82f8f8..7e53fe5fd 100644 --- a/README_ko.md +++ b/README_ko.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## 스타 기록 -🎉 **GitHub 스타 30,000개, 감사합니다!** +🎉 **GitHub 스타 40,000개, 감사합니다!** REA를 사용하고, 버그를 보고하고, 기능을 요청하고, 빌드를 테스트하고, 수정에 기여해 주신 모든 분께 감사드립니다. diff --git a/README_pl.md b/README_pl.md index 54f5aeb64..b80f04918 100644 --- a/README_pl.md +++ b/README_pl.md @@ -256,7 +256,7 @@ Zgłaszaj podatności zgodnie z [SECURITY.md](SECURITY.md). ## Historia gwiazdek -🎉 **30 000 gwiazdek na GitHubie — dziękujemy!** +🎉 **40 000 gwiazdek na GitHubie — dziękujemy!** Dziękujemy wszystkim, którzy używają REA, zgłaszają błędy, proponują nowe funkcje, testują kompilacje i przesyłają poprawki. diff --git a/README_pt-BR.md b/README_pt-BR.md index 1d3c627ca..89b1820a5 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -256,7 +256,7 @@ Relate vulnerabilidades conforme [SECURITY.md](SECURITY.md). ## Histórico de estrelas -🎉 **30.000 estrelas no GitHub — muito obrigado!** +🎉 **40.000 estrelas no GitHub — muito obrigado!** Obrigado a todos que usam o REA, relatam bugs, sugerem funcionalidades, testam builds e contribuem com correções. diff --git a/README_ru.md b/README_ru.md index f88603244..6dc2815f7 100644 --- a/README_ru.md +++ b/README_ru.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## История звёзд -🎉 **30 000 звёзд на GitHub — спасибо!** +🎉 **40 000 звёзд на GitHub — спасибо!** Спасибо всем, кто использует REA, сообщает об ошибках, предлагает новые функции, тестирует сборки и помогает с исправлениями. diff --git a/README_th.md b/README_th.md index dcbcaee28..d23d4998b 100644 --- a/README_th.md +++ b/README_th.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## ประวัติดาว -🎉 **30,000 ดาวบน GitHub — ขอบคุณทุกคน!** +🎉 **40,000 ดาวบน GitHub — ขอบคุณทุกคน!** ขอบคุณทุกคนที่ใช้ REA รายงานบั๊ก เสนอฟีเจอร์ ทดสอบบิลด์ และช่วยแก้ไข diff --git a/README_tr.md b/README_tr.md index b77512bed..43d502a2b 100644 --- a/README_tr.md +++ b/README_tr.md @@ -256,7 +256,7 @@ Güvenlik açıklarını [SECURITY.md](SECURITY.md) üzerinden bildirin. ## Yıldız geçmişi -🎉 **GitHub'da 30.000 yıldız — teşekkürler!** +🎉 **GitHub'da 40.000 yıldız — teşekkürler!** REA'yı kullanan, hata bildiren, özellik talep eden, derlemeleri test eden ve düzeltmelere katkıda bulunan herkese teşekkürler. diff --git a/README_uk.md b/README_uk.md index d9224f713..1a6352867 100644 --- a/README_uk.md +++ b/README_uk.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## Історія зірок -🎉 **30 000 зірок на GitHub — дякуємо!** +🎉 **40 000 зірок на GitHub — дякуємо!** Дякуємо всім, хто використовує REA, повідомляє про помилки, пропонує нові функції, тестує збірки й допомагає з виправленнями. diff --git a/README_vi.md b/README_vi.md index 7004fe5da..a3d492724 100644 --- a/README_vi.md +++ b/README_vi.md @@ -256,7 +256,7 @@ Báo cáo lỗ hổng theo [SECURITY.md](SECURITY.md). ## Lịch sử sao -🎉 **30.000 sao trên GitHub — xin cảm ơn!** +🎉 **40.000 sao trên GitHub — xin cảm ơn!** Cảm ơn mọi người đã sử dụng REA, báo lỗi, đề xuất tính năng, kiểm thử bản dựng và đóng góp bản sửa lỗi. diff --git a/README_zh-TW.md b/README_zh-TW.md index e5b6275bf..8317d1c36 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## Star 歷史 -🎉 **GitHub Star 達到 30,000 個,感謝大家!** +🎉 **GitHub Star 達到 40,000 個,感謝大家!** 感謝每一位使用 REA、報告錯誤、提出功能需求、測試建置和貢獻修復的朋友。 diff --git a/README_zh.md b/README_zh.md index 3d7034742..710773ad3 100644 --- a/README_zh.md +++ b/README_zh.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## Star 历史 -🎉 **GitHub Star 达到 30,000 个,感谢大家!** +🎉 **GitHub Star 达到 40,000 个,感谢大家!** 感谢每一位使用 REA、报告错误、提出功能需求、测试构建和贡献修复的朋友。 From 87f0051496aff1b05ab24d6b63f79884f4ca9b8f Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:48:36 +0800 Subject: [PATCH 021/189] refactor(providers): use canonical artifact and managed identities --- src/application/InvestigationProviders.ts | 8 +++--- src/artifacts/ArtifactProvider.ts | 28 +++++++++---------- src/artifacts/ArtifactProviderMetadata.ts | 11 ++------ src/composition/auxiliaryAnalysisProviders.ts | 16 +++++------ src/dotnet/ManagedStaticProvider.ts | 22 ++++++++------- src/dotnet/ManagedStaticProviderMetadata.ts | 11 ++------ 6 files changed, 40 insertions(+), 56 deletions(-) diff --git a/src/application/InvestigationProviders.ts b/src/application/InvestigationProviders.ts index 03d705252..4861272a0 100644 --- a/src/application/InvestigationProviders.ts +++ b/src/application/InvestigationProviders.ts @@ -24,18 +24,18 @@ export const workflowAnalysisProfile = ( }); /** Provider identity for deterministic artifact inventories. */ -export const ARTIFACT_GRAPH_PROVIDER = { +export const ARTIFACT_GRAPH_PROVIDER = Object.freeze({ id: "rea-artifact-graph", name: "REA safe artifact graph provider", version: "1", -} as const; +} as const); /** Provider identity for execution-free managed PE/CLI analysis. */ -export const MANAGED_STATIC_PROVIDER = { +export const MANAGED_STATIC_PROVIDER = Object.freeze({ id: "rea-dotnet-static", name: "REA managed static analysis provider", version: "1", -} as const; +} as const); /** Provider identity for deterministic managed-code comparison workflows. */ export const MANAGED_WORKFLOW_PROVIDER = { diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index e4b514a4f..fe5d24ef0 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -33,10 +33,8 @@ import type { JsonValue } from "../domain/jsonValue.js"; import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js"; import { err, ok, type Result } from "../domain/result.js"; import { ArtifactReaderFailure } from "./ArtifactReader.js"; -import { - ARTIFACT_PROVIDER_IDENTITY as IDENTITY, - artifactCapabilities, -} from "./ArtifactProviderMetadata.js"; +import { artifactCapabilities } from "./ArtifactProviderMetadata.js"; +import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js"; import { createEvidence } from "../domain/evidence.js"; import { createArtifactInspection } from "../domain/artifactInspection.js"; @@ -56,7 +54,7 @@ export class ArtifactProvider implements AnalysisProvider { } identity(): ProviderIdentity { - return IDENTITY; + return ARTIFACT_GRAPH_PROVIDER; } capabilities(): readonly CapabilityDescriptor[] { @@ -81,11 +79,11 @@ class ArtifactClient implements AnalysisClient { options?: ExecutionOptions, ) { if (operation === "health") - return ok(createAnalysisExecution(null, IDENTITY)); + return ok(createAnalysisExecution(null, ARTIFACT_GRAPH_PROVIDER)); if (!isArtifactOperation(operation)) return err( new AnalysisCapabilityUnavailableError( - IDENTITY.id, + ARTIFACT_GRAPH_PROVIDER.id, operation, "Operation is not implemented by artifact graph provider.", ), @@ -113,7 +111,7 @@ class ArtifactClient implements AnalysisClient { ...(options?.signal === undefined ? {} : { signal: options.signal }), }); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { limitations: result.limitations, locations: result.documents.map(({ relative_path: path }) => ({ kind: "artifact-path" as const, @@ -166,7 +164,7 @@ class ArtifactClient implements AnalysisClient { `Active archive digest changed: expected ${this.target.sha256}, observed ${result.archive_sha256}`, ); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { limitations: result.limitations, locations: [{ kind: "artifact-path", path: result.archive_path }], }), @@ -189,7 +187,7 @@ class ArtifactClient implements AnalysisClient { options?.signal, ); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { rawResult: null, limitations: result.limitations, subject: subjectFor( @@ -206,7 +204,7 @@ class ArtifactClient implements AnalysisClient { const parsed = artifactInventoryInputSchema.parse(parameters); const result = await this.inventory(parsed, options); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { rawResult: null, limitations: result.limitations, subject: subjectFor( @@ -262,7 +260,7 @@ class ArtifactClient implements AnalysisClient { ...(options?.signal === undefined ? {} : { signal: options.signal }), }); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { limitations: result.limitations, locations: result.catalogs.map(({ path }) => ({ kind: "artifact-path" as const, @@ -296,7 +294,7 @@ class ArtifactClient implements AnalysisClient { ...(options?.signal === undefined ? {} : { signal: options.signal }), }); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { limitations: result.limitations, locations: result.images.map(({ path }) => ({ kind: "artifact-path" as const, @@ -329,7 +327,7 @@ class ArtifactClient implements AnalysisClient { kind: "artifact-path" as const, path, })); - const inventoryEvidence = createEvidence(subject, IDENTITY, { + const inventoryEvidence = createEvidence(subject, ARTIFACT_GRAPH_PROVIDER, { operation: "inventory_artifact", parameters: inventoryParameters, result: inventory, @@ -345,7 +343,7 @@ class ArtifactClient implements AnalysisClient { message: "inventory substep completed", }); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, ARTIFACT_GRAPH_PROVIDER, { rawResult: null, limitations: result.limitations, subject, diff --git a/src/artifacts/ArtifactProviderMetadata.ts b/src/artifacts/ArtifactProviderMetadata.ts index aa36eeaf4..dc138f94d 100644 --- a/src/artifacts/ArtifactProviderMetadata.ts +++ b/src/artifacts/ArtifactProviderMetadata.ts @@ -1,14 +1,7 @@ -import type { - CapabilityDescriptor, - ProviderIdentity, -} from "../application/AnalysisProvider.js"; +import type { CapabilityDescriptor } from "../application/AnalysisProvider.js"; import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js"; import { ARTIFACT_ANALYSIS_OPERATIONS } from "../contracts/artifactToolContracts.js"; -/** Identity of artifact inventory and owned extraction observations. */ -export const ARTIFACT_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze( - ARTIFACT_GRAPH_PROVIDER, -); /** Declare artifact coverage without constructing readers or acquiring resources. */ export const artifactCapabilities = ( platform: NodeJS.Platform = process.platform, @@ -16,7 +9,7 @@ export const artifactCapabilities = ( Object.freeze( ARTIFACT_ANALYSIS_OPERATIONS.map((operation) => { const common = { - provider: ARTIFACT_PROVIDER_IDENTITY, + provider: ARTIFACT_GRAPH_PROVIDER, operation, effects: Object.freeze({ mutatesArtifact: false, diff --git a/src/composition/auxiliaryAnalysisProviders.ts b/src/composition/auxiliaryAnalysisProviders.ts index 7e6b797b4..c094b6d9f 100644 --- a/src/composition/auxiliaryAnalysisProviders.ts +++ b/src/composition/auxiliaryAnalysisProviders.ts @@ -1,13 +1,11 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import type { LazyAnalysisProvider } from "../application/binary/LazyAnalysisProvider.js"; +import { artifactCapabilities } from "../artifacts/ArtifactProviderMetadata.js"; import { - ARTIFACT_PROVIDER_IDENTITY, - artifactCapabilities, -} from "../artifacts/ArtifactProviderMetadata.js"; -import { - MANAGED_STATIC_PROVIDER_IDENTITY, - managedStaticCapabilities, -} from "../dotnet/ManagedStaticProviderMetadata.js"; + ARTIFACT_GRAPH_PROVIDER, + MANAGED_STATIC_PROVIDER, +} from "../application/InvestigationProviders.js"; +import { managedStaticCapabilities } from "../dotnet/ManagedStaticProviderMetadata.js"; import { NATIVE_MACOS_PROVIDER_IDENTITY, nativeMacOSCapabilities, @@ -25,7 +23,7 @@ export const auxiliaryAnalysisProviderDeclarations = ( const environment = snapshotEnvironment(selectedEnvironment, platform); return [ { - identity: ARTIFACT_PROVIDER_IDENTITY, + identity: ARTIFACT_GRAPH_PROVIDER, capabilities: artifactCapabilities(platform), load: async () => { const { ArtifactProvider } = @@ -43,7 +41,7 @@ export const auxiliaryAnalysisProviderDeclarations = ( }, }, { - identity: MANAGED_STATIC_PROVIDER_IDENTITY, + identity: MANAGED_STATIC_PROVIDER, capabilities: managedStaticCapabilities(), load: async () => { const { ManagedStaticProvider } = diff --git a/src/dotnet/ManagedStaticProvider.ts b/src/dotnet/ManagedStaticProvider.ts index 60c75b8f9..68f0c0696 100644 --- a/src/dotnet/ManagedStaticProvider.ts +++ b/src/dotnet/ManagedStaticProvider.ts @@ -11,10 +11,8 @@ import { type ExecutionOptions, type ProviderIdentity, } from "../application/AnalysisProvider.js"; -import { - MANAGED_STATIC_PROVIDER_IDENTITY as IDENTITY, - managedStaticCapabilities, -} from "./ManagedStaticProviderMetadata.js"; +import { managedStaticCapabilities } from "./ManagedStaticProviderMetadata.js"; +import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js"; import { MANAGED_TOOL_CONTRACTS, managedTargetInputSchema, @@ -46,7 +44,7 @@ export class ManagedStaticProvider implements AnalysisProvider { managedStaticCapabilities(); identity(): ProviderIdentity { - return IDENTITY; + return MANAGED_STATIC_PROVIDER; } capabilities(): readonly CapabilityDescriptor[] { @@ -69,11 +67,11 @@ class ManagedStaticClient implements AnalysisClient { options?: ExecutionOptions, ) { if (operation === "health") - return ok(createAnalysisExecution(null, IDENTITY)); + return ok(createAnalysisExecution(null, MANAGED_STATIC_PROVIDER)); if (!isManagedOperation(operation)) return err( new AnalysisCapabilityUnavailableError( - IDENTITY.id, + MANAGED_STATIC_PROVIDER.id, operation, "Operation is not implemented by the managed static provider.", ), @@ -81,7 +79,7 @@ class ManagedStaticClient implements AnalysisClient { if (this.target.format !== "pe") return err( new AnalysisCapabilityUnavailableError( - IDENTITY.id, + MANAGED_STATIC_PROVIDER.id, operation, `Managed static triage requires a PE target; observed ${this.target.format}.`, ), @@ -111,7 +109,7 @@ class ManagedStaticClient implements AnalysisClient { this.target, ); return ok( - createAnalysisExecution(result, IDENTITY, { + createAnalysisExecution(result, MANAGED_STATIC_PROVIDER, { rawResult: null, limitations: result.limitations, subject: this.target, @@ -121,7 +119,11 @@ class ManagedStaticClient implements AnalysisClient { } catch (cause: unknown) { if (options?.signal?.aborted === true) return err(new AnalysisCancelledError(operation)); - return err(new ProviderAdapterError(IDENTITY.id, operation, { cause })); + return err( + new ProviderAdapterError(MANAGED_STATIC_PROVIDER.id, operation, { + cause, + }), + ); } } diff --git a/src/dotnet/ManagedStaticProviderMetadata.ts b/src/dotnet/ManagedStaticProviderMetadata.ts index 04b412828..a346cee5c 100644 --- a/src/dotnet/ManagedStaticProviderMetadata.ts +++ b/src/dotnet/ManagedStaticProviderMetadata.ts @@ -1,23 +1,16 @@ -import type { - CapabilityDescriptor, - ProviderIdentity, -} from "../application/AnalysisProvider.js"; +import type { CapabilityDescriptor } from "../application/AnalysisProvider.js"; import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js"; import { MANAGED_TOOL_CONTRACTS, type ManagedToolName, } from "../contracts/managed/managedToolContracts.js"; -/** Identity of execution-free managed metadata observations. */ -export const MANAGED_STATIC_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze( - MANAGED_STATIC_PROVIDER, -); /** Declare managed metadata coverage without opening or loading an assembly. */ export const managedStaticCapabilities = (): readonly CapabilityDescriptor[] => Object.freeze( MANAGED_TOOL_CONTRACTS.map((contract) => Object.freeze({ - provider: MANAGED_STATIC_PROVIDER_IDENTITY, + provider: MANAGED_STATIC_PROVIDER, operation: contract.name, available: true as const, reason: null, From d1983a45767bfcdc020652f48109a78a3f9fa590 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:48:49 +0800 Subject: [PATCH 022/189] refactor(browser): open scenario sessions without a factory wrapper --- src/browser/BrowserScenarioSessionPort.ts | 13 ++-- .../PlaywrightBrowserScenarioProvider.test.ts | 62 +++++++++---------- .../PlaywrightBrowserScenarioProvider.ts | 10 +-- src/browser/PlaywrightScenarioBrowser.ts | 2 +- src/browser/PlaywrightScenarioSession.ts | 21 +------ src/composition/browserScenario.ts | 6 +- 6 files changed, 45 insertions(+), 69 deletions(-) diff --git a/src/browser/BrowserScenarioSessionPort.ts b/src/browser/BrowserScenarioSessionPort.ts index ea2fa0838..92299c049 100644 --- a/src/browser/BrowserScenarioSessionPort.ts +++ b/src/browser/BrowserScenarioSessionPort.ts @@ -35,11 +35,8 @@ export interface BrowserScenarioSessionPort { redactError(error: unknown): string; } -export interface BrowserScenarioSessionFactory { - open( - scenario: BrowserScenario, - options?: { - readonly signal?: AbortSignal; - }, - ): Promise; -} +/** Acquire one scenario session whose lifecycle the caller owns. */ +export type BrowserScenarioSessionOpener = ( + scenario: BrowserScenario, + options: { readonly signal?: AbortSignal }, +) => Promise; diff --git a/src/browser/PlaywrightBrowserScenarioProvider.test.ts b/src/browser/PlaywrightBrowserScenarioProvider.test.ts index fd3cd8869..b66cecb20 100644 --- a/src/browser/PlaywrightBrowserScenarioProvider.test.ts +++ b/src/browser/PlaywrightBrowserScenarioProvider.test.ts @@ -221,9 +221,9 @@ describe("PlaywrightBrowserScenarioProvider", () => { it("makes reported event gaps ineligible for equality even in launch mode", async () => { const session = new FakeSession("launch"); session.eventGaps = ["Popup frames before discovery are unavailable"]; - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario( scenario({ events: ["frames"] }), ); @@ -237,9 +237,9 @@ describe("PlaywrightBrowserScenarioProvider", () => { }); it("returns an initial state and every step beyond the former action ceiling", async () => { const session = new FakeSession("launch"); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario({ actions: 129 })); if (!result.ok) throw result.error; expect(result.value.scenario.action_count).toBe(129); @@ -249,9 +249,9 @@ describe("PlaywrightBrowserScenarioProvider", () => { it("makes missing and truncated captures ineligible for equality", async () => { const session = new FakeSession("launch", { incomplete: true }); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario( scenario({ captures: ["screenshot", "dom"] }), ); @@ -268,9 +268,9 @@ describe("PlaywrightBrowserScenarioProvider", () => { const session = new FakeSession("launch", { action: new Error("fixture secret action failure"), }); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario({ actions: 2 })); if (!result.ok) throw result.error; expect(result.value.steps.map(({ status }) => status)).toEqual([ @@ -288,9 +288,9 @@ describe("PlaywrightBrowserScenarioProvider", () => { it("disconnects external CDP sessions and marks pre-attach events missing", async () => { const session = new FakeSession("connect"); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario( scenario({ mode: "connect" }), ); @@ -314,9 +314,9 @@ describe("PlaywrightBrowserScenarioProvider cleanup", () => { action: new Error("fixture secret action failure"), close: new Error("browser close failed"), }); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario()); expect(result.ok).toBe(false); @@ -378,9 +378,9 @@ describe("PlaywrightBrowserScenarioProvider operation failures", () => { url: sanitizeBrowserUrl("https://app.example.test/"), }, ]; - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario()); expect(result.ok).toBe(false); @@ -462,9 +462,9 @@ describe("PlaywrightBrowserScenarioProvider cancellation and timeout", () => { const session = new FakeSession("launch", { capture: { call: 1, error }, }); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario()); expect(result.ok).toBe(false); @@ -489,11 +489,9 @@ describe("PlaywrightBrowserScenarioProvider cancellation and timeout", () => { describe("PlaywrightBrowserScenarioProvider request cancellation", () => { it("does not open a session for an already-cancelled request", async () => { let opens = 0; - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => { - opens += 1; - return Promise.resolve(new FakeSession("launch")); - }, + const provider = new PlaywrightBrowserScenarioProvider(() => { + opens += 1; + return Promise.resolve(new FakeSession("launch")); }); const controller = new AbortController(); controller.abort(); @@ -508,9 +506,9 @@ describe("PlaywrightBrowserScenarioProvider request cancellation", () => { const controller = new AbortController(); const session = new FakeSession("launch"); session.onPerform = () => controller.abort(); - const provider = new PlaywrightBrowserScenarioProvider({ - open: () => Promise.resolve(session), - }); + const provider = new PlaywrightBrowserScenarioProvider(() => + Promise.resolve(session), + ); const result = await provider.captureScenario(scenario(), { signal: controller.signal, }); diff --git a/src/browser/PlaywrightBrowserScenarioProvider.ts b/src/browser/PlaywrightBrowserScenarioProvider.ts index b62d3504f..8a8c75b7c 100644 --- a/src/browser/PlaywrightBrowserScenarioProvider.ts +++ b/src/browser/PlaywrightBrowserScenarioProvider.ts @@ -25,7 +25,7 @@ import { BrowserObservationError } from "../domain/browserObservationError.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { err, ok, type Result } from "../domain/result.js"; import type { - BrowserScenarioSessionFactory, + BrowserScenarioSessionOpener, BrowserScenarioSessionPort, } from "./BrowserScenarioSessionPort.js"; import { @@ -226,14 +226,14 @@ const globalCompleteness = ( }; const runScenario = async ( - factory: BrowserScenarioSessionFactory, + openSession: BrowserScenarioSessionOpener, scenario: BrowserScenario, options: ExecutionOptions, ): Promise => { if (options.signal?.aborted === true) throw new BrowserObservationError(OPERATION, "cancelled"); const startedAt = Date.now(); - const session = await factory.open( + const session = await openSession( scenario, options.signal === undefined ? {} : { signal: options.signal }, ); @@ -337,7 +337,7 @@ const runScenario = async ( /** Controlled Playwright/CDP scenario driver with exact process ownership. */ export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapturePort { - constructor(private readonly factory: BrowserScenarioSessionFactory) {} + constructor(private readonly openSession: BrowserScenarioSessionOpener) {} identity(): ProviderIdentity { return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY; @@ -348,7 +348,7 @@ export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapture options: ExecutionOptions = {}, ): Promise> { try { - return ok(await runScenario(this.factory, scenario, options)); + return ok(await runScenario(this.openSession, scenario, options)); } catch (cause: unknown) { if (cause instanceof AnalysisError) return err(cause); return err( diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts index 4cfdf2653..10942cbe2 100644 --- a/src/browser/PlaywrightScenarioBrowser.ts +++ b/src/browser/PlaywrightScenarioBrowser.ts @@ -25,7 +25,7 @@ export interface OpenedScenarioBrowser { } /** Provider actions retained until the owned browser and profile are released. */ -export interface PlaywrightScenarioCleanupResources { +interface PlaywrightScenarioCleanupResources { readonly closeBrowser: () => Promise; readonly removeProfile: (() => Promise) | undefined; } diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.ts index 1c31ef344..26aa65fcd 100644 --- a/src/browser/PlaywrightScenarioSession.ts +++ b/src/browser/PlaywrightScenarioSession.ts @@ -3,10 +3,7 @@ import { type BrowserContext, type Page } from "playwright-core"; import type { BrowserScenario } from "../domain/browserScenario.js"; import type { BrowserScenarioAction } from "../domain/browserScenarioValues.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; -import type { - BrowserScenarioSessionFactory, - BrowserScenarioSessionPort, -} from "./BrowserScenarioSessionPort.js"; +import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js"; import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js"; import { failBrowserScenarioOperation, @@ -311,19 +308,3 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort { ); } } - -/** Production Playwright/CDP session factory. */ -export class PlaywrightScenarioSessionFactory implements BrowserScenarioSessionFactory { - constructor( - private readonly environment: Readonly>, - ) {} - - open( - scenario: BrowserScenario, - options: { - readonly signal?: AbortSignal; - } = {}, - ): Promise { - return PlaywrightScenarioSession.open(scenario, this.environment, options); - } -} diff --git a/src/composition/browserScenario.ts b/src/composition/browserScenario.ts index 14d78c209..8a4aa5bc9 100644 --- a/src/composition/browserScenario.ts +++ b/src/composition/browserScenario.ts @@ -1,11 +1,11 @@ import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js"; import { PlaywrightBrowserScenarioProvider } from "../browser/PlaywrightBrowserScenarioProvider.js"; -import { PlaywrightScenarioSessionFactory } from "../browser/PlaywrightScenarioSession.js"; +import { PlaywrightScenarioSession } from "../browser/PlaywrightScenarioSession.js"; /** Construct a fresh provider without opening a target or acquiring an engine. */ export const createBrowserScenarioProvider = ( environment: Readonly>, ): BrowserScenarioCapturePort => - new PlaywrightBrowserScenarioProvider( - new PlaywrightScenarioSessionFactory(environment), + new PlaywrightBrowserScenarioProvider((scenario, options) => + PlaywrightScenarioSession.open(scenario, environment, options), ); From 070339af50a50a0f23e82db859e761c53277ee79 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:48:49 +0800 Subject: [PATCH 023/189] refactor(process): remove duplicate observation and trace entry points --- src/domain/process/processTraceEvaluation.ts | 6 +-- .../process/processTraceSpecification.ts | 9 +---- src/process/ProcessOwnershipObservation.ts | 37 ++++++------------- 3 files changed, 15 insertions(+), 37 deletions(-) diff --git a/src/domain/process/processTraceEvaluation.ts b/src/domain/process/processTraceEvaluation.ts index be0406680..51a2a15f8 100644 --- a/src/domain/process/processTraceEvaluation.ts +++ b/src/domain/process/processTraceEvaluation.ts @@ -4,6 +4,7 @@ import type { JsonValue } from "../jsonValue.js"; import type { ProcessCapture } from "./processCaptureParsing.js"; import { processSourceTruncated } from "./processCaptureCoverage.js"; import { + comparableProcessObservationPayload, processObservationLocationSchema, projectProcessObservation, type ProcessObservationLocation, @@ -11,7 +12,6 @@ import { } from "./processObservation.js"; import { canonicalTraceJson, - comparableTracePayload, processTraceCardinalityBounds, type ProcessTraceSpecification, } from "./processTraceSpecification.js"; @@ -190,7 +190,7 @@ const matchRecords = ( ignoredFieldsBySource.set(event.source, ignoredFields); eventsByKey.set( `${event.source}\0${canonicalTraceJson( - comparableTracePayload(event.exact, ignoredFields), + comparableProcessObservationPayload(event.exact, ignoredFields), )}`, event, ); @@ -198,7 +198,7 @@ const matchRecords = ( for (const record of records) { const match = eventsByKey.get( `${record.source}\0${canonicalTraceJson( - comparableTracePayload( + comparableProcessObservationPayload( record.payload, ignoredFieldsBySource.get(record.source), ), diff --git a/src/domain/process/processTraceSpecification.ts b/src/domain/process/processTraceSpecification.ts index ba3139572..0f121c42b 100644 --- a/src/domain/process/processTraceSpecification.ts +++ b/src/domain/process/processTraceSpecification.ts @@ -7,7 +7,6 @@ import { jsonValueSchema } from "../jsonValue.js"; import { comparableProcessObservationPayload, processObservationSourceSchema, - type ProcessObservationSource, } from "./processObservation.js"; const identifierSchema = z.string().regex(IDENTIFIER_PATTERN); @@ -114,12 +113,6 @@ export const canonicalTraceJson = (value: unknown): string => { return serialized; }; -/** Remove only explicitly declared schedule metadata before exact matching. */ -export const comparableTracePayload = ( - value: unknown, - ignoredFields: readonly string[] = [], -): unknown => comparableProcessObservationPayload(value, ignoredFields); - export const processTraceCardinalityBounds = ( cardinality: ProcessTraceSpecification["events"][number]["cardinality"], ): readonly [number, number] => { @@ -472,7 +465,7 @@ export const processTraceSpecificationSchema = path: ["events", index, "exact"], }); const predicate = `${event.source}\0${canonicalTraceJson( - comparableTracePayload(event.exact, ignoredFields), + comparableProcessObservationPayload(event.exact, ignoredFields), )}`; if (predicates.has(predicate)) context.addIssue({ diff --git a/src/process/ProcessOwnershipObservation.ts b/src/process/ProcessOwnershipObservation.ts index 661363bfe..34edeaea9 100644 --- a/src/process/ProcessOwnershipObservation.ts +++ b/src/process/ProcessOwnershipObservation.ts @@ -16,9 +16,9 @@ import type { } from "./ProcessOwnership.js"; /** Observe one group without signaling it, failing closed on identity doubt. */ -export const observeOwnedProcessGroupWithHost = async ( +export const observeOwnedProcessGroup = async ( ownership: OwnedProcessGroup, - host: ProcessOwnershipHost, + host: ProcessOwnershipHost = systemProcessOwnershipHost, signal?: AbortSignal, ): Promise => { signal?.throwIfAborted(); @@ -60,10 +60,16 @@ export const observeOwnedProcessGroupWithHost = async ( return { state: "alive" }; }; -/** Record the live launcher and descendant lineage after run-token validation. */ -export const observeOwnedProcessLineageWithHost = async ( +/** + * Record the live launcher and descendant lineage after run-token validation. + * + * The observation is intentionally point-in-time. A verified empty descendant + * list means no descendants were live during this observation, not that the + * run never created a short-lived child. + */ +export const observeOwnedProcessLineage = async ( ownership: OwnedProcessGroup, - host: ProcessOwnershipHost, + host: ProcessOwnershipHost = systemProcessOwnershipHost, ): Promise => { let processes: readonly ProcessTableEntry[]; try { @@ -439,27 +445,6 @@ export const prepareProcessOwnershipInspection = async ( await systemProcessOwnershipHost.prepare?.(signal); }; -/** Observe one group without signaling it, failing closed on identity doubt. */ -export const observeOwnedProcessGroup = async ( - ownership: OwnedProcessGroup, - host: ProcessOwnershipHost = systemProcessOwnershipHost, - signal?: AbortSignal, -): Promise => - observeOwnedProcessGroupWithHost(ownership, host, signal); - -/** - * Record the live launcher and descendant lineage after run-token validation. - * - * The observation is intentionally point-in-time. A verified empty descendant - * list means no descendants were live during this observation, not that the - * run never created a short-lived child. - */ -export const observeOwnedProcessLineage = async ( - ownership: OwnedProcessGroup, - host: ProcessOwnershipHost = systemProcessOwnershipHost, -): Promise => - observeOwnedProcessLineageWithHost(ownership, host); - const processIsGone = async ( host: ProcessOwnershipHost, pid: number, From 4144e454f385c372d29e301e6bb959092c606a6e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:48:49 +0800 Subject: [PATCH 024/189] refactor: remove single-use forwarding helpers --- src/domain/analysisView/analysisView.ts | 7 +------ src/dotnet/ManagedMemberInstructionDecoder.ts | 7 +------ src/server/createServer.ts | 5 +++-- src/server/registerNativeTools.ts | 21 ------------------- 4 files changed, 5 insertions(+), 35 deletions(-) delete mode 100644 src/server/registerNativeTools.ts diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index c0d33a862..efb9f5d44 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -208,11 +208,6 @@ export const analysisViewInputError = ( ): AnalysisInputError => new AnalysisInputError(INSPECT_ANALYSIS_VIEW_OPERATION, undefined, issues); -/** SHA-256 of the canonical projected JSON, excluding this digest field. */ -export const analysisViewDigest = ( - projection: Omit, -): string => digestCanonicalValue(projection, "Analysis view"); - /** View payload before the content digest is attached. */ export type UnsignedAnalysisView = | Omit< @@ -229,7 +224,7 @@ export const sealAnalysisView = ( ): AnalysisViewResult => analysisViewResultSchema.parse({ ...projection, - view_digest: analysisViewDigest(projection), + view_digest: digestCanonicalValue(projection, "Analysis view"), }); const parentDigest = (evidenceId: string): string => evidenceId.slice(3); diff --git a/src/dotnet/ManagedMemberInstructionDecoder.ts b/src/dotnet/ManagedMemberInstructionDecoder.ts index 7c8a11a05..49f240a88 100644 --- a/src/dotnet/ManagedMemberInstructionDecoder.ts +++ b/src/dotnet/ManagedMemberInstructionDecoder.ts @@ -4,11 +4,6 @@ import type { ParsedInstruction, } from "./ManagedMemberInspectorCore.js"; -const opcode = ( - code: number, -): { readonly name: string; readonly operand: string } | undefined => - OPCODES.get(code); - const PREFIX_OPCODES = new Set([ "unaligned.", "volatile.", @@ -403,7 +398,7 @@ export const decodeInstructions = ( const first = il.readUInt8(offset); offset += 1; const code = first === 0xfe ? 0xfe00 + il.readUInt8(offset++) : first; - const descriptor = opcode(code); + const descriptor = OPCODES.get(code); if (descriptor === undefined) { issue = `Unsupported CIL opcode 0x${code.toString(16)} at IL offset ${String(start)}`; break; diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 20fae3fd2..b578e26c5 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -61,7 +61,8 @@ import { AndroidAnalysisService } from "../application/android/AndroidAnalysisSe import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js"; import { createAndroidAnalysisProvider } from "../composition/android.js"; import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js"; -import { registerNativeTools } from "./registerNativeTools.js"; +import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js"; +import { registerEvidenceTools } from "./registerEvidenceTools.js"; import { registerOfficialTools } from "./registerOfficialTools.js"; import { registerGuidedPrompts } from "./registerPrompts.js"; import { registerSessionTools } from "./registerSessionTools.js"; @@ -410,7 +411,7 @@ const registerBinaryAnalysisTools = ({ recordEvidence, withAdmittedAnalysis, }; - registerNativeTools(server, evidenceOptions); + registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, evidenceOptions); registerArtifactTools(server, evidenceOptions); registerManagedTools(server, evidenceOptions); if (session !== undefined) diff --git a/src/server/registerNativeTools.ts b/src/server/registerNativeTools.ts deleted file mode 100644 index ba244a8e3..000000000 --- a/src/server/registerNativeTools.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; -import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; - -import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js"; -import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; -import type { Logger } from "pino"; -import { registerEvidenceTools } from "./registerEvidenceTools.js"; - -/** Register provider-neutral static inspection operations. */ -export const registerNativeTools = ( - server: EvidenceMcpServer, - options: { - readonly logger: Logger; - readonly activeTarget: (() => BinaryTarget | undefined) | undefined; - readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined; - readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis; - }, -): void => - registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, { - ...options, - }); From 8c96baab80dc258d31ca1632d761fffb11dbaaae Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:48:49 +0800 Subject: [PATCH 025/189] refactor(catalog): import CLI metadata from its owner --- scripts/lib/catalog-cli.d.mts | 12 ++++++++++++ scripts/lib/product-catalog.d.mts | 19 ------------------- scripts/lib/product-catalog.mjs | 17 ++--------------- .../cli/cliInputSchemaRequired.test.ts | 2 +- tests/boundary/cli/cliToolCoverage.test.ts | 2 +- tests/boundary/cli/productCatalog.test.ts | 19 ++----------------- 6 files changed, 18 insertions(+), 53 deletions(-) create mode 100644 scripts/lib/catalog-cli.d.mts diff --git a/scripts/lib/catalog-cli.d.mts b/scripts/lib/catalog-cli.d.mts new file mode 100644 index 000000000..1362b58aa --- /dev/null +++ b/scripts/lib/catalog-cli.d.mts @@ -0,0 +1,12 @@ +export function createCliInventory(cli: unknown): { + readonly primary: readonly string[]; + readonly aliases: readonly { + readonly name: string; + readonly target: string; + }[]; +}; +export function cliCommandOptionNames( + cli: unknown, + name: string, +): readonly string[]; +export function cliCommandDescriptionIssues(cli: unknown): readonly string[]; diff --git a/scripts/lib/product-catalog.d.mts b/scripts/lib/product-catalog.d.mts index b260cd2e6..7147d4040 100644 --- a/scripts/lib/product-catalog.d.mts +++ b/scripts/lib/product-catalog.d.mts @@ -26,10 +26,6 @@ export interface ProductCatalog { readonly format: string; readonly configuration: string; }[]; - readonly schemas: readonly { - readonly id: string; - readonly version: string | number; - }[]; readonly cli: { readonly primary_count: number; readonly commands: readonly string[]; @@ -45,21 +41,6 @@ export interface ProductCatalog { } export function createProductCatalog(root: string): Promise; -export function providerCatalogDigest( - providers: ProductCatalog["providers"], -): string; -export function createCliInventory(cli: unknown): { - readonly primary: readonly string[]; - readonly aliases: readonly { - readonly name: string; - readonly target: string; - }[]; -}; -export function cliCommandOptionNames( - cli: unknown, - name: string, -): readonly string[]; -export function cliCommandDescriptionIssues(cli: unknown): readonly string[]; export function serializeProductCatalog( catalog: ProductCatalog, ): Promise; diff --git a/scripts/lib/product-catalog.mjs b/scripts/lib/product-catalog.mjs index ebdaaeb0d..dadffaf7d 100644 --- a/scripts/lib/product-catalog.mjs +++ b/scripts/lib/product-catalog.mjs @@ -1,22 +1,9 @@ import { formatGeneratedFile } from "./format-generated-file.mjs"; import { assertSameNames, digest, loadSources } from "./catalog-core.mjs"; -import { - createCliInventory, - cliCommandDescriptionIssues, - cliCommandOptionNames, -} from "./catalog-cli.mjs"; +import { createCliInventory } from "./catalog-cli.mjs"; import { providerCatalog, toolFamilyCatalog } from "./catalog-builders.mjs"; -export { - createCliInventory, - cliCommandDescriptionIssues, - cliCommandOptionNames, -}; - -/** Return the stable digest for the source-derived provider projection. */ -export const providerCatalogDigest = (providers) => digest(providers); - /** Project current runtime contracts into deterministic, machine-readable facts. */ export const createProductCatalog = async (root) => { const sources = await loadSources(root); @@ -59,7 +46,7 @@ export const createProductCatalog = async (root) => { counts: sources.catalogIdentity.CATALOG_IDENTITY.counts, digests: { // Full runtime schema digests belong to server identity, not this facts projection. - providers_sha256: providerCatalogDigest(providers), + providers_sha256: digest(providers), }, }, }; diff --git a/tests/boundary/cli/cliInputSchemaRequired.test.ts b/tests/boundary/cli/cliInputSchemaRequired.test.ts index 3bc95236f..a74a3e963 100644 --- a/tests/boundary/cli/cliInputSchemaRequired.test.ts +++ b/tests/boundary/cli/cliInputSchemaRequired.test.ts @@ -3,7 +3,7 @@ import { Cli, z } from "incur"; import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { createCliInventory } from "../../../scripts/lib/product-catalog.mjs"; +import { createCliInventory } from "../../../scripts/lib/catalog-cli.mjs"; type CliInstance = ReturnType; type CommandMap = NonNullable>; diff --git a/tests/boundary/cli/cliToolCoverage.test.ts b/tests/boundary/cli/cliToolCoverage.test.ts index 729d9bce2..b689ecfbb 100644 --- a/tests/boundary/cli/cliToolCoverage.test.ts +++ b/tests/boundary/cli/cliToolCoverage.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { createCliInventory } from "../../../scripts/lib/product-catalog.mjs"; +import { createCliInventory } from "../../../scripts/lib/catalog-cli.mjs"; import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js"; import { CLI_COMMAND_ALIASES, diff --git a/tests/boundary/cli/productCatalog.test.ts b/tests/boundary/cli/productCatalog.test.ts index f1fca8401..3f35fc830 100644 --- a/tests/boundary/cli/productCatalog.test.ts +++ b/tests/boundary/cli/productCatalog.test.ts @@ -27,8 +27,9 @@ import { createCliInventory, cliCommandDescriptionIssues, cliCommandOptionNames, +} from "../../../scripts/lib/catalog-cli.mjs"; +import { createProductCatalog, - providerCatalogDigest, serializeProductCatalog, } from "../../../scripts/lib/product-catalog.mjs"; @@ -77,9 +78,6 @@ describe("canonical product catalog", () => { catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id) ?.capabilities, ).toEqual([...GHIDRA_OPERATIONS].sort()); - expect(catalog.runtime_catalog.digests.providers_sha256).toBe( - providerCatalogDigest(catalog.providers), - ); expect( JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")), ).toEqual(catalog); @@ -207,19 +205,6 @@ describe("canonical product catalog drift", () => { ); }); - it("changes the provider projection digest when provider facts drift", async () => { - const catalog = await createProductCatalog(root); - const firstProvider = catalog.providers[0]; - if (firstProvider === undefined) throw new TypeError("Missing provider"); - const driftedProviders = [ - { ...firstProvider, name: `${firstProvider.name} drifted` }, - ...catalog.providers.slice(1), - ]; - expect(providerCatalogDigest(driftedProviders)).not.toBe( - catalog.runtime_catalog.digests.providers_sha256, - ); - }); - it("fails check mode without rewriting a stale generated artifact", async () => { const directory = await createTestTempDirectory("rea-generated-check-"); temporaryRoots.push(directory); From 5e8fb531e255a4a04fc053c54096f66d5c84cde3 Mon Sep 17 00:00:00 2001 From: dakjdakd <1428823446@qq.com> Date: Fri, 9 Oct 2026 23:45:58 +0800 Subject: [PATCH 026/189] fix(artifacts): reject incomplete inventoried extraction --- .../extraction/ArtifactExtraction.ts | 29 ++++- ...actProvider.extractionCompleteness.test.ts | 118 ++++++++++++++++++ 2 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts index b87beb09a..9bfdd13b4 100644 --- a/src/artifacts/extraction/ArtifactExtraction.ts +++ b/src/artifacts/extraction/ArtifactExtraction.ts @@ -57,6 +57,9 @@ export const extractArtifact = async ( const selectedIds = new Set( selectedOccurrences.map(({ occurrence_id: id }) => id), ); + const regularPaths = new Set( + selectedOccurrences.map(({ logical_path: path }) => path), + ); const occurrences = new Map(); const neededNodes = new Set(); collectOccurrences( @@ -98,11 +101,25 @@ export const extractArtifact = async ( ); return { occurrence, node }; }); + const activeSelected = selected.filter(({ occurrence }) => { + // Nested members remain represented by their containing regular file; + // only entries exposed by the active reader are materialized. + let path = occurrence.logical_path; + for ( + let slash = path.lastIndexOf("/"); + slash >= 0; + slash = path.lastIndexOf("/") + ) { + path = path.slice(0, slash); + if (regularPaths.has(path)) return false; + } + return true; + }); return materializeSelection({ input, sourcePath, inventory, - selected, + selected: activeSelected, signal, }); }; @@ -143,7 +160,6 @@ const materializeSelection = async ({ const extracted: ExtractedOccurrence[] = []; try { output = await SafeOutputTree.create(input.outputRoot); - const materialized: SelectedOccurrence[] = []; const registry = new ArtifactPathRegistry(); for await (const entry of reader.entries(signal)) { const path = normalizeArtifactPath(entry.path); @@ -172,8 +188,13 @@ const materializeSelection = async ({ bytes_written: written.bytesWritten, created: true, }); - materialized.push(selectedItem); + byPath.delete(path); } + if (byPath.size > 0) + throw new ArtifactReaderFailure( + "integrity", + `Inventoried regular artifact entries were not materialized: ${[...byPath.keys()].sort(compareUnicodeCodePoints).join(", ")}`, + ); readerCloseAttempted = true; await reader.close(); readerClosed = true; @@ -183,7 +204,7 @@ const materializeSelection = async ({ const result = createExtractionResult( input, inventory, - materialized, + selected, extracted, ); await output.commit(); diff --git a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts new file mode 100644 index 000000000..0a160a1da --- /dev/null +++ b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts @@ -0,0 +1,118 @@ +import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { createPackage } from "@electron/asar"; +import { expect, it, onTestFinished, vi } from "vitest"; + +import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js"; +import { SafeOutputTree } from "../../../../src/artifacts/SafeOutputTree.js"; +import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js"; +import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; + +it.each(["file", "directory"] as const)( + "rolls back when an inventoried %s disappears before extraction", + async (removedKind) => { + const root = await createTestTempDirectory("rea-extract-missing-"); + const source = join(root, "source"); + await mkdir(join(source, "z"), { recursive: true }); + // Equal bytes share an artifact node, but both occurrences must be copied. + await writeFile(join(source, "a.txt"), "same bytes\n"); + await writeFile(join(source, "z", "missing.txt"), "same bytes\n"); + const output = join(root, "output"); + afterInventory(async () => { + await rm( + removedKind === "file" + ? join(source, "z", "missing.txt") + : join(source, "z"), + { recursive: removedKind === "directory" }, + ); + }); + + const result = await extract(source, output); + if (result.ok) throw new Error("Incomplete extraction must fail"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "artifact_operation_failed", + details: { + operation: "extract_artifact", + reason: "integrity", + detail: + "Inventoried regular artifact entries were not materialized: z/missing.txt", + }, + }); + await expect(access(output)).rejects.toThrow(); + expect(await readFile(join(source, "a.txt"), "utf8")).toBe("same bytes\n"); + }, +); + +it("still refuses a regular file added after inventory and rolls back", async () => { + const root = await createTestTempDirectory("rea-extract-added-"); + const source = join(root, "source"); + await mkdir(source); + await writeFile(join(source, "a.txt"), "original\n"); + const output = join(root, "output"); + afterInventory(async () => { + await writeFile(join(source, "z.txt"), "new\n"); + }); + const result = await extract(source, output); + if (result.ok) throw new Error("Changed inventory must fail"); + expect(projectAnalysisError(result.error)).toMatchObject({ + details: { + reason: "integrity", + detail: "Regular artifact entry is missing from inventory: z.txt", + }, + }); + await expect(access(output)).rejects.toThrow(); +}); + +it("preserves every equal-content occurrence and copies a nested ASAR as its containing file", async () => { + const root = await createTestTempDirectory("rea-extract-nested-"); + const source = join(root, "source"); + const nested = join(root, "nested"); + await mkdir(source); + await mkdir(join(nested, "assets"), { recursive: true }); + await writeFile(join(nested, "assets", "main.js"), "export default 1;\n"); + await createPackage(nested, join(source, "app.asar")); + await writeFile(join(source, "a.txt"), "same bytes\n"); + await writeFile(join(source, "b.txt"), "same bytes\n"); + const output = join(root, "output"); + const result = await extract(source, output); + if (!result.ok) throw result.error; + const extracted = artifactExtractionResultSchema.parse(result.value.result); + expect(extracted.artifacts.map(({ relative_path }) => relative_path)).toEqual( + ["a.txt", "app.asar", "b.txt"], + ); + expect(extracted.extraction_manifest.selected_occurrence_ids).toHaveLength(3); + expect(extracted.artifacts[0]?.artifact_id).toBe( + extracted.artifacts[2]?.artifact_id, + ); + for (const path of ["a.txt", "b.txt", "app.asar"]) + expect(await readFile(join(output, path))).toEqual( + await readFile(join(source, path)), + ); +}); + +// Synchronize a real filesystem change after the actual inventory scan. The +// production reader, writes, failure translation and rollback all remain real. +const afterInventory = (change: () => Promise): void => { + const create = SafeOutputTree.create; + const hook = vi + .spyOn(SafeOutputTree, "create") + .mockImplementationOnce(async (...args) => { + const output = await create(...args); + await change(); + return output; + }); + onTestFinished(() => hook.mockRestore()); +}; + +const extract = (source: string, output: string) => + new ArtifactProvider(process.env) + .createClient({ + path: source, + sourcePath: source, + sha256: "0".repeat(64), + kind: "archive", + format: "asar", + }) + .execute("extract_artifact", { output_root: output }); From a0523b375eb3147f1d2d1e7eb10a2f4546f5d0fc Mon Sep 17 00:00:00 2001 From: dakjdakd <1428823446@qq.com> Date: Fri, 9 Oct 2026 23:47:10 +0800 Subject: [PATCH 027/189] fix(browser): retain attached scenario emulation until cleanup --- docs/testing.md | 5 + scripts/fixtures/browser-verifier-site.mjs | 14 ++ .../lib/browser-scenario-environment-e2e.mjs | 200 ++++++++++++++++++ scripts/verify-real-browser.mjs | 7 + src/browser/PlaywrightScenarioBrowser.ts | 30 ++- 5 files changed, 240 insertions(+), 16 deletions(-) create mode 100644 scripts/lib/browser-scenario-environment-e2e.mjs diff --git a/docs/testing.md b/docs/testing.md index 9079160a1..76d09d7af 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -281,6 +281,11 @@ regressions until a real fixture establishes equivalent coverage. decoding. Its SDK client explicitly permits the larger inline JSON response; this lane does not establish large image-comparison request transport coverage. +The scenario checks read locale, timezone, device scale and viewport dimensions +from actual page JavaScript through CLI and stdio MCP DOM captures. They also +verify that attached-page emulation is released after success, initialization +failure, action failure and cancellation while the external target stays open. + `verify:browser:network` is a focused real-browser lane for transaction identity, selected request/response bytes, binary and compressed responses, duplicate headers, credential and declared-secret redaction, redirects, streaming cutoff, diff --git a/scripts/fixtures/browser-verifier-site.mjs b/scripts/fixtures/browser-verifier-site.mjs index 7a5095e52..208a314a2 100644 --- a/scripts/fixtures/browser-verifier-site.mjs +++ b/scripts/fixtures/browser-verifier-site.mjs @@ -11,6 +11,20 @@ export async function startBrowserVerifierSite() { response.destroy(); return; } + if (request.url === "/scenario-environment") { + response.setHeader("content-type", "text/html"); + response.end(`

+        `);
+      return;
+    }
     if (request.url === "/slow-json") {
       response.setHeader("content-type", "application/json");
       response.write('{"pending":');
diff --git a/scripts/lib/browser-scenario-environment-e2e.mjs b/scripts/lib/browser-scenario-environment-e2e.mjs
new file mode 100644
index 000000000..bc460192d
--- /dev/null
+++ b/scripts/lib/browser-scenario-environment-e2e.mjs
@@ -0,0 +1,200 @@
+import assert from "node:assert/strict";
+import { setTimeout as delay } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { Client } from "@modelcontextprotocol/client";
+import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
+
+import { CdpConnection } from "../../dist/browser/CdpConnection.js";
+import { createBrowserScenarioProvider } from "../../dist/composition/browserScenario.js";
+import { browserScenarioSchema } from "../../dist/domain/browserScenario.js";
+import { runScenarioCli } from "./browser-scenario-verifier.mjs";
+import { requireMcpEvidenceResult } from "./mcp-verifier-results.mjs";
+
+const expected = {
+  timezone: "Pacific/Honolulu",
+  locale: "fr-FR",
+  dpr: 2,
+  width: 900,
+  height: 600,
+};
+const expression = `JSON.stringify({
+  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+  locale: Intl.DateTimeFormat().resolvedOptions().locale,
+  dpr: devicePixelRatio, width: innerWidth, height: innerHeight
+})`;
+
+const environmentScenario = (endpoint, targetId, origin) =>
+  browserScenarioSchema.parse({
+    browser: { mode: "connect", cdp_endpoint: endpoint, target_id: targetId },
+    start_url: { url: `${origin}/scenario-environment` },
+    environment: {
+      locale: expected.locale,
+      timezone: expected.timezone,
+      viewport: {
+        width: expected.width,
+        height: expected.height,
+        device_scale_factor: expected.dpr,
+      },
+    },
+    actions: [
+      {
+        step_id: "refresh",
+        action: "click",
+        locator: { kind: "css", selector: "#refresh-environment" },
+      },
+    ],
+    capture: { after_each_step: ["dom"], at_end: ["dom"] },
+  });
+
+const assertCapture = (capture) => {
+  assert.equal(capture.browser.cleanup, "disconnected-external");
+  for (const step of capture.steps) {
+    assert.equal(step.artifacts.dom.state, "captured");
+    const text = step.artifacts.dom.value.text;
+    const observed = /
([^<]+)<\/pre>/u.exec(text);
+    assert.ok(observed, "DOM omitted the page's actual environment values");
+    assert.deepEqual(JSON.parse(observed[1]), expected);
+  }
+};
+
+/** Verify actual attached-page emulation and restoration across scenario outcomes. */
+export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
+  const targets = await (await fetch(`${endpoint}/json/list`)).json();
+  const target = targets.find(({ id }) => id === targetId);
+  assert.ok(target, "External fixture target is missing");
+  const connection = await CdpConnection.connect(
+    target.webSocketDebuggerUrl,
+    "capture_browser_scenario",
+  );
+  const readEnvironment = async () => {
+    const value = await connection.send("Runtime.evaluate", {
+      expression,
+      returnByValue: true,
+    });
+    assert.equal(value.result.type, "string");
+    return JSON.parse(value.result.value);
+  };
+  const baseline = await readEnvironment();
+  const scenario = environmentScenario(endpoint, targetId, origin);
+  const assertRestored = async () => {
+    assert.deepEqual(await readEnvironment(), baseline);
+    const remaining = await (await fetch(`${endpoint}/json/list`)).json();
+    assert.ok(remaining.some(({ id }) => id === targetId));
+  };
+  try {
+    assertCapture((await runScenarioCli(scenario)).normalized_result);
+    await assertRestored();
+    const transport = new StdioClientTransport({
+      command: process.execPath,
+      args: [fileURLToPath(new URL("../rea.mjs", import.meta.url)), "mcp"],
+      env: process.env,
+      stderr: "pipe",
+    });
+    const client = new Client({
+      name: "browser-environment-e2e",
+      version: "1",
+    });
+    try {
+      await client.connect(transport);
+      assertCapture(
+        requireMcpEvidenceResult(
+          await client.callTool({
+            name: "capture_browser_scenario",
+            arguments: scenario,
+          }),
+          "capture_browser_scenario",
+        ),
+      );
+    } finally {
+      await client.close();
+      await transport.close();
+    }
+    await assertRestored();
+    const provider = createBrowserScenarioProvider(process.env);
+    const initializationFailure = await provider.captureScenario({
+      ...scenario,
+      environment: { ...scenario.environment, timezone: "REA/Invalid" },
+    });
+    assert.equal(initializationFailure.ok, false);
+    await assertRestored();
+    const waiting = browserScenarioSchema.parse({
+      ...scenario,
+      actions: [
+        {
+          step_id: "missing",
+          action: "wait_for",
+          locator: { kind: "css", selector: "#missing-environment-element" },
+          state: "visible",
+          timeout_ms: 100,
+        },
+      ],
+    });
+    const actionFailure = await provider.captureScenario(waiting);
+    assert.equal(actionFailure.ok, true);
+    assertCapture(actionFailure.value);
+    assert.equal(actionFailure.value.steps.at(-1).status, "failed");
+    await assertRestored();
+    await verifyCancelledEnvironment(
+      provider,
+      connection,
+      waiting,
+      readEnvironment,
+    );
+    await assertRestored();
+    return {
+      mocked: false,
+      cli: true,
+      stdio_mcp: true,
+      observed: expected,
+      restored: baseline,
+      initialization_failure_cleanup: true,
+      action_failure_cleanup: true,
+      cancellation_cleanup: true,
+      external_target_preserved: true,
+    };
+  } finally {
+    await connection.close();
+  }
+}
+
+async function verifyCancelledEnvironment(
+  provider,
+  connection,
+  scenario,
+  readEnvironment,
+) {
+  const controller = new AbortController();
+  const priorNavigation = await connection.send("Runtime.evaluate", {
+    expression: "performance.timeOrigin",
+    returnByValue: true,
+  });
+  const pending = provider.captureScenario(
+    { ...scenario, actions: [{ ...scenario.actions[0], timeout_ms: 30_000 }] },
+    { signal: controller.signal },
+  );
+  try {
+    const deadline = Date.now() + 10_000;
+    while (true) {
+      const navigation = await connection.send("Runtime.evaluate", {
+        expression: "performance.timeOrigin",
+        returnByValue: true,
+      });
+      if (
+        navigation.result.value !== priorNavigation.result.value &&
+        JSON.stringify(await readEnvironment()) === JSON.stringify(expected)
+      )
+        break;
+      assert.ok(Date.now() < deadline, "Scenario never applied emulation");
+      await delay(25);
+    }
+    await delay(100);
+  } finally {
+    controller.abort();
+  }
+  const cancelled = await pending;
+  assert.ok(
+    !cancelled.ok ||
+      cancelled.value.steps.some(({ status }) => status === "cancelled"),
+    "Cancellation unexpectedly completed every action",
+  );
+}
diff --git a/scripts/verify-real-browser.mjs b/scripts/verify-real-browser.mjs
index 5f05981d6..4dd492854 100644
--- a/scripts/verify-real-browser.mjs
+++ b/scripts/verify-real-browser.mjs
@@ -44,6 +44,7 @@ import { verifyBrowserModules } from "./lib/browser-module-e2e.mjs";
 import { verifyBrowserDomDestinations } from "./lib/browser-dom-destinations-e2e.mjs";
 import { verifyBrowserCaptureMetadataBudget } from "./lib/browser-capture-metadata-budget-e2e.mjs";
 import { artifactCliEvidence, artifactMcpResult } from "./lib/artifact-e2e.mjs";
+import { verifyScenarioEnvironment } from "./lib/browser-scenario-environment-e2e.mjs";
 
 const REAL_BROWSER_STARTUP_TIMEOUT_MS = 60_000;
 const SCENARIO_SECRET_VALUE = "rea-browser-verifier-secret";
@@ -274,6 +275,11 @@ try {
     throw new Error("Scenario attachment terminated its external browser");
 
   const profilesBefore = await scenarioProfiles();
+  const scenarioEnvironment = await verifyScenarioEnvironment(
+    endpoint,
+    target,
+    site.origin,
+  );
   const launchedScenario = await createBrowserScenarioProvider(
     process.env,
   ).captureScenario(
@@ -366,6 +372,7 @@ try {
     browserScenarioAttachCleanup: "disconnected-external",
     browserScenarioLaunchCleanup: "terminated-owned-process",
     scenarioFailure,
+    scenarioEnvironment,
     verified: true,
   };
 } finally {
diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts
index 10942cbe2..392c96278 100644
--- a/src/browser/PlaywrightScenarioBrowser.ts
+++ b/src/browser/PlaywrightScenarioBrowser.ts
@@ -173,22 +173,20 @@ const configureAttachedEnvironment = async (
     reducedMotion: scenario.environment.reduced_motion,
   });
   const session = await context.newCDPSession(page);
-  try {
-    await session.send("Emulation.setDeviceMetricsOverride", {
-      width: scenario.environment.viewport.width,
-      height: scenario.environment.viewport.height,
-      deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
-      mobile: false,
-    });
-    await session.send("Emulation.setLocaleOverride", {
-      locale: scenario.environment.locale,
-    });
-    await session.send("Emulation.setTimezoneOverride", {
-      timezoneId: scenario.environment.timezone,
-    });
-  } finally {
-    await session.detach();
-  }
+  // Chromium resets these overrides when the CDP session detaches. Keep it on
+  // the scenario transport until cleanup disconnects the attached browser.
+  await session.send("Emulation.setDeviceMetricsOverride", {
+    width: scenario.environment.viewport.width,
+    height: scenario.environment.viewport.height,
+    deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
+    mobile: false,
+  });
+  await session.send("Emulation.setLocaleOverride", {
+    locale: scenario.environment.locale,
+  });
+  await session.send("Emulation.setTimezoneOverride", {
+    timezoneId: scenario.environment.timezone,
+  });
 };
 
 /** Preserve an operation failure while reporting any incomplete cleanup. */

From 4896adcd0f9316034e83129685ed3807ade6f3ea Mon Sep 17 00:00:00 2001
From: Rudy Celekli 
Date: Fri, 9 Oct 2026 12:09:15 -0400
Subject: [PATCH 028/189] fix(javascript): parse declaration artifacts in
 ambient mode

---
 .../JavaScriptApplicationDeclarations.test.ts | 54 +++++++++++++++++++
 .../javascript/javascriptSourceParser.ts      | 15 +++---
 2 files changed, 63 insertions(+), 6 deletions(-)
 create mode 100644 src/application/javascript/JavaScriptApplicationDeclarations.test.ts

diff --git a/src/application/javascript/JavaScriptApplicationDeclarations.test.ts b/src/application/javascript/JavaScriptApplicationDeclarations.test.ts
new file mode 100644
index 000000000..30a80bb62
--- /dev/null
+++ b/src/application/javascript/JavaScriptApplicationDeclarations.test.ts
@@ -0,0 +1,54 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
+import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
+
+it.each(["types.d.ts", "types.d.mts", "types.d.cts"])(
+  "keeps valid ambient declarations complete in %s",
+  async (path) => {
+    const root = await createTestTempDirectory("rea-declaration-file-");
+    const source = "export const value: number;\n";
+    await writeFile(join(root, path), source);
+    const result = await analyzeJavaScriptApplication({
+      input_path: root,
+      format: "directory",
+    });
+    if (!result.ok) throw result.error;
+    const analysis = javascriptApplicationAnalysisResultSchema.parse(
+      result.value.normalized_result,
+    );
+    expect(analysis.graph.coverage.status).toBe("complete");
+    expect(parseJavaScriptSource(source, path)?.errors).toEqual([]);
+  },
+);
+
+it("retains the missing-initializer diagnostic for ordinary TypeScript", () => {
+  const errors = parseJavaScriptSource(
+    "export const value: number;",
+    "types.ts",
+  )?.errors;
+  expect(errors?.map(({ message }) => message)).toContain(
+    "Missing initializer in const declaration. (1:26)",
+  );
+});
+
+it("keeps CommonJS TypeScript angle-bracket assertions complete", async () => {
+  const root = await createTestTempDirectory("rea-cts-assertion-");
+  const source = "export const value = 42;\n";
+  await writeFile(join(root, "app.cts"), source);
+  const result = await analyzeJavaScriptApplication({
+    input_path: root,
+    format: "directory",
+  });
+  if (!result.ok) throw result.error;
+  const analysis = javascriptApplicationAnalysisResultSchema.parse(
+    result.value.normalized_result,
+  );
+  expect(analysis.graph.coverage.status).toBe("complete");
+  expect(parseJavaScriptSource(source, "app.cts")?.errors).toEqual([]);
+});
diff --git a/src/domain/javascript/javascriptSourceParser.ts b/src/domain/javascript/javascriptSourceParser.ts
index e86b1bca3..86d030bc3 100644
--- a/src/domain/javascript/javascriptSourceParser.ts
+++ b/src/domain/javascript/javascriptSourceParser.ts
@@ -1,4 +1,4 @@
-import { parse } from "@babel/parser";
+import { parse, type ParserPlugin } from "@babel/parser";
 
 /** Babel AST produced by REA's inert JavaScript parser boundary. */
 export type ParsedJavaScriptSource = ReturnType;
@@ -8,6 +8,10 @@ export const parseJavaScriptSource = (
   source: string,
   sourcePath?: string,
 ): ParsedJavaScriptSource | null => {
+  const typescript: ParserPlugin = [
+    "typescript",
+    { dts: /\.d\.(?:ts|mts|cts)$/iu.test(sourcePath ?? "") },
+  ];
   try {
     return parse(source, {
       sourceType: "unambiguous",
@@ -17,12 +21,11 @@ export const parseJavaScriptSource = (
       // forms, including parameter decorators. Without it a decorated
       // TypeScript source fails to parse at all rather than reporting
       // recovered syntax, which loses every fact derived from that source.
-      // Plain .ts artifacts admit angle-bracket type assertions instead of JSX.
+      // Plain .ts and .cts artifacts admit angle-bracket type assertions instead of JSX.
       // Unknown paths retain the existing JSX-capable parser contract.
-      plugins:
-        sourcePath?.toLowerCase().endsWith(".ts") === true
-          ? ["decorators-legacy", "typescript"]
-          : ["decorators-legacy", "jsx", "typescript"],
+      plugins: /\.(?:ts|cts)$/iu.test(sourcePath ?? "")
+        ? ["decorators-legacy", typescript]
+        : ["decorators-legacy", "jsx", typescript],
     });
   } catch (cause: unknown) {
     // Unparseable source is represented by the null return.

From e995b19f834ba78faa294f5959fd3ad8a97290ca Mon Sep 17 00:00:00 2001
From: Rudy Celekli 
Date: Fri, 9 Oct 2026 12:20:29 -0400
Subject: [PATCH 029/189] fix(javascript): preserve semantic evidence through
 satisfies

---
 .../JavaScriptApplicationSatisfies.test.ts    | 57 +++++++++++++++++++
 .../javascriptSemanticCallResolution.ts       |  3 +-
 .../javascript/javascriptSemanticReturns.ts   |  3 +-
 .../javascript/javascriptSemanticValues.ts    |  3 +-
 4 files changed, 63 insertions(+), 3 deletions(-)
 create mode 100644 src/application/javascript/JavaScriptApplicationSatisfies.test.ts

diff --git a/src/application/javascript/JavaScriptApplicationSatisfies.test.ts b/src/application/javascript/JavaScriptApplicationSatisfies.test.ts
new file mode 100644
index 000000000..8507180f1
--- /dev/null
+++ b/src/application/javascript/JavaScriptApplicationSatisfies.test.ts
@@ -0,0 +1,57 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
+import { topLevelBinding } from "../../domain/javascript/javascriptSemanticAnalysis.fixture.js";
+import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
+
+it.each([
+  '"ready" satisfies string',
+  '("ready" satisfies string) as string',
+  '("ready" satisfies string)!',
+])("retains the runtime primitive through %s", (expression) => {
+  const ir = analyzeJavaScriptSemantics(`const value = ${expression};`);
+  expect(topLevelBinding(ir, "value").value).toEqual({
+    status: "literal",
+    value: "ready",
+  });
+});
+
+it("retains exported constant evidence through a type-only satisfies expression", async () => {
+  const root = await createTestTempDirectory("rea-ts-satisfies-");
+  await writeFile(
+    join(root, "app.ts"),
+    'export const value = "ready" satisfies string;\n',
+  );
+  const result = await analyzeJavaScriptApplication({
+    input_path: root,
+    format: "directory",
+  });
+  if (!result.ok) throw result.error;
+  const analysis = javascriptApplicationAnalysisResultSchema.parse(
+    result.value.normalized_result,
+  );
+  expect(
+    analysis.semantic_graph.nodes.filter(
+      ({ kind, properties }) =>
+        kind === "literal" && properties.value === "ready",
+    ),
+  ).toHaveLength(1);
+});
+
+it("retains local call targets and exported callable links through satisfies", () => {
+  const ir = analyzeJavaScriptSemantics(
+    'export const render = (() => "ready") satisfies (() => string); render();',
+  );
+  const callable = ir.callables[0];
+  if (callable === undefined) throw new Error("Missing callable");
+  expect(
+    ir.moduleLinks.find(({ localName }) => localName === "render")?.callableId,
+  ).toBe(callable.callableId);
+  expect(ir.callSites[0]?.calleeCallableIds).toEqual([callable.callableId]);
+  expect(ir.callSites[0]?.resolution).toBe("exact");
+});
diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts
index 246472301..24673279a 100644
--- a/src/domain/javascript/javascriptSemanticCallResolution.ts
+++ b/src/domain/javascript/javascriptSemanticCallResolution.ts
@@ -62,7 +62,8 @@ const resolveCallables = (
   if (
     t.isTSAsExpression(node) ||
     t.isTSTypeAssertion(node) ||
-    t.isTSNonNullExpression(node)
+    t.isTSNonNullExpression(node) ||
+    t.isTSSatisfiesExpression(node)
   )
     return resolveCallables(node.expression, context);
   if (t.isConditionalExpression(node) || t.isLogicalExpression(node))
diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts
index 5a1a3f415..13e68279a 100644
--- a/src/domain/javascript/javascriptSemanticReturns.ts
+++ b/src/domain/javascript/javascriptSemanticReturns.ts
@@ -188,7 +188,8 @@ const callableIdsForNode = (
   if (
     t.isTSAsExpression(node) ||
     t.isTSTypeAssertion(node) ||
-    t.isTSNonNullExpression(node)
+    t.isTSNonNullExpression(node) ||
+    t.isTSSatisfiesExpression(node)
   )
     return callableIdsForNode(node.expression, state, admitted, seen);
   return [];
diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts
index 791d3c388..2fdebe512 100644
--- a/src/domain/javascript/javascriptSemanticValues.ts
+++ b/src/domain/javascript/javascriptSemanticValues.ts
@@ -199,7 +199,8 @@ const evaluateExpression = (
   if (
     (t.isTSAsExpression(node) ||
       t.isTSTypeAssertion(node) ||
-      t.isTSNonNullExpression(node)) &&
+      t.isTSNonNullExpression(node) ||
+      t.isTSSatisfiesExpression(node)) &&
     t.isExpression(node.expression)
   )
     return evaluateExpression(node.expression, nestedContext(context));

From 2bd7de6f8ca62fc1d48334cfa7fdced461b7b153 Mon Sep 17 00:00:00 2001
From: Rudy Celekli 
Date: Fri, 9 Oct 2026 12:09:42 -0400
Subject: [PATCH 030/189] fix(javascript): retain distinct module provenance
 path components

---
 ...vascriptSemanticAnalysis.origin_paths.test.ts | 16 ++++++++++++++++
 .../javascript/javascriptSemanticProvenance.ts   |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)
 create mode 100644 src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts

diff --git a/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts
new file mode 100644
index 000000000..c3e12d327
--- /dev/null
+++ b/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts
@@ -0,0 +1,16 @@
+import { expect, it } from "vitest";
+
+import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
+import { topLevelBinding } from "./javascriptSemanticAnalysis.fixture.js";
+
+it("retains distinct module origins when a property contains the old separator", () => {
+  const result = analyzeJavaScriptSemantics(
+    'import * as ns from "./fixture.js"; const selected = choice ? ns["a\\0b"] : ns.a.b;',
+  );
+  const provenance = topLevelBinding(result, "selected").provenance;
+  expect(provenance.status).toBe("ambiguous");
+  expect(provenance.origins.map(({ importedPath }) => importedPath)).toEqual(
+    expect.arrayContaining([["a\0b"], ["a", "b"]]),
+  );
+  expect(provenance.origins).toHaveLength(2);
+});
diff --git a/src/domain/javascript/javascriptSemanticProvenance.ts b/src/domain/javascript/javascriptSemanticProvenance.ts
index 218c465b5..ab56a1488 100644
--- a/src/domain/javascript/javascriptSemanticProvenance.ts
+++ b/src/domain/javascript/javascriptSemanticProvenance.ts
@@ -48,7 +48,7 @@ export const uniqueSemanticOrigins = (
   );
 
 const semanticOriginKey = (origin: JavaScriptModuleOrigin): string =>
-  `${origin.specifier}\0${origin.importedPath.join("\0")}`;
+  JSON.stringify([origin.specifier, origin.importedPath]);
 
 /** Canonically distinguish primitive values across type boundaries. */
 export const semanticPrimitiveKey = (

From 9055bd695b75f72fb1b8a538d1485d30c0b0ee0b Mon Sep 17 00:00:00 2001
From: Rudy Celekli 
Date: Fri, 9 Oct 2026 12:14:53 -0400
Subject: [PATCH 031/189] fix(javascript): avoid positive-zero evidence for
 signed zero

---
 .../JavaScriptApplicationSignedZero.test.ts   | 26 ++++++++++++++
 ...scriptSemanticAnalysis.signed_zero.test.ts | 35 +++++++++++++++++++
 .../javascriptSemanticPrimitives.ts           |  5 +++
 .../javascript/javascriptSemanticValues.ts    |  5 ++-
 4 files changed, 70 insertions(+), 1 deletion(-)
 create mode 100644 src/application/javascript/JavaScriptApplicationSignedZero.test.ts
 create mode 100644 src/domain/javascript/javascriptSemanticAnalysis.signed_zero.test.ts

diff --git a/src/application/javascript/JavaScriptApplicationSignedZero.test.ts b/src/application/javascript/JavaScriptApplicationSignedZero.test.ts
new file mode 100644
index 000000000..b1f4df0ba
--- /dev/null
+++ b/src/application/javascript/JavaScriptApplicationSignedZero.test.ts
@@ -0,0 +1,26 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
+
+it("does not expose a resolved positive-zero literal for a negative-zero export", async () => {
+  const root = await createTestTempDirectory("rea-signed-zero-");
+  await writeFile(join(root, "app.js"), "export const value = -0;\n");
+  const result = await analyzeJavaScriptApplication({
+    input_path: root,
+    format: "directory",
+  });
+  if (!result.ok) throw result.error;
+  const analysis = javascriptApplicationAnalysisResultSchema.parse(
+    result.value.normalized_result,
+  );
+  expect(
+    analysis.semantic_graph.nodes.filter(
+      ({ kind, properties }) => kind === "literal" && properties.value === 0,
+    ),
+  ).toEqual([]);
+});
diff --git a/src/domain/javascript/javascriptSemanticAnalysis.signed_zero.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.signed_zero.test.ts
new file mode 100644
index 000000000..6dfbd0dfe
--- /dev/null
+++ b/src/domain/javascript/javascriptSemanticAnalysis.signed_zero.test.ts
@@ -0,0 +1,35 @@
+import { expect, it } from "vitest";
+
+import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
+import { topLevelBinding } from "./javascriptSemanticAnalysis.fixture.js";
+import { semanticPrimitiveSet } from "./javascriptSemanticPrimitives.js";
+
+it.each(["-0", "-0.0", "-0x0", "-0 * 5", "-1 * 0", '+"-0"'])(
+  "does not publish positive zero evidence for %s",
+  (expression) => {
+    const ir = analyzeJavaScriptSemantics(
+      `export const value = ${expression};`,
+    );
+    expect(topLevelBinding(ir, "value").value).toMatchObject({
+      status: "unknown",
+    });
+  },
+);
+
+it("does not collapse a possible negative-zero branch into positive-zero certainty", () => {
+  const ir = analyzeJavaScriptSemantics("const value = choice ? -0 : 0;");
+  expect(topLevelBinding(ir, "value").value.status).not.toBe("literal");
+  expect(semanticPrimitiveSet([-0, 0])).toMatchObject({ status: "unknown" });
+});
+
+it.each([
+  { expression: "0", value: 0 },
+  { expression: "-1", value: -1 },
+  { expression: '"-0"', value: "-0" },
+])("preserves representable primitive $expression", ({ expression, value }) => {
+  const ir = analyzeJavaScriptSemantics(`const value = ${expression};`);
+  expect(topLevelBinding(ir, "value").value).toEqual({
+    status: "literal",
+    value,
+  });
+});
diff --git a/src/domain/javascript/javascriptSemanticPrimitives.ts b/src/domain/javascript/javascriptSemanticPrimitives.ts
index 29cff687b..abb1f015c 100644
--- a/src/domain/javascript/javascriptSemanticPrimitives.ts
+++ b/src/domain/javascript/javascriptSemanticPrimitives.ts
@@ -21,6 +21,11 @@ export const semanticPrimitiveSet = (
         status: "unknown",
         reason: "Nonfinite numbers are outside the JSON primitive lattice.",
       };
+    if (typeof value === "number" && Object.is(value, -0))
+      return {
+        status: "unknown",
+        reason: "Negative zero cannot be preserved by JSON primitive evidence.",
+      };
     uniqueValues.add(value);
     if (uniqueValues.size > SEMANTIC_PRIMITIVE_CANDIDATE_LIMIT)
       return semanticResourceLimitUnknown("primitive-candidates");
diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts
index 2fdebe512..d0eb007b5 100644
--- a/src/domain/javascript/javascriptSemanticValues.ts
+++ b/src/domain/javascript/javascriptSemanticValues.ts
@@ -171,7 +171,10 @@ const evaluateExpression = (
   if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT)
     return semanticResourceLimitUnknown("expression-depth");
   const literal = readExactJavaScriptLiteral(node);
-  if (literal.found) return { status: "literal", value: literal.value };
+  if (literal.found)
+    return typeof literal.value === "number"
+      ? primitiveSet([literal.value])
+      : { status: "literal", value: literal.value };
   if (t.isIdentifier(node)) {
     const binding = resolveSemanticBindingState(context.state, node, node.name);
     return binding === undefined

From f166a2ae15b072216173a51a8f5cad930a858366 Mon Sep 17 00:00:00 2001
From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
Date: Fri, 9 Oct 2026 11:53:47 -0400
Subject: [PATCH 032/189] fix(reference): report malformed UTF-8 before import
 parsing

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
---
 docs/cli.md                                   |  4 +
 src/domain/referenceSourceImportParsing.ts    | 20 ++++-
 .../boundary/cli/referenceSourceUtf8.test.ts  | 77 +++++++++++++++++++
 3 files changed, 100 insertions(+), 1 deletion(-)
 create mode 100644 tests/boundary/cli/referenceSourceUtf8.test.ts

diff --git a/docs/cli.md b/docs/cli.md
index 87792e7c0..51a45c462 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -147,6 +147,10 @@ from observations of the current app. File names do not automatically exclude
 files. Set `REA_REFERENCE_SECRET_PATTERNS_JSON` to a JSON array of ignore
 patterns when you want to exclude selected paths.
 
+JavaScript and TypeScript import parsing requires valid UTF-8. Malformed source
+bytes retain their original hashes and sizes with a decoding diagnostic; REA
+does not infer module targets from replacement characters.
+
 Historical-source import requires safe no-follow file opens on Linux or
 macOS. Native Windows returns `unsupported_host`; use Linux REA inside WSL
 or another supported host. See
diff --git a/src/domain/referenceSourceImportParsing.ts b/src/domain/referenceSourceImportParsing.ts
index 70097297a..7f9ad996a 100644
--- a/src/domain/referenceSourceImportParsing.ts
+++ b/src/domain/referenceSourceImportParsing.ts
@@ -331,7 +331,25 @@ export const parseReferenceSourceImports = (
   if (language !== null && !codeSourceLanguages.has(language))
     return { relationships: [], parse_failures: [] };
 
-  const source = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
+  let source: string;
+  try {
+    source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+  } catch (cause: unknown) {
+    // The import still records the original bytes; lossy text cannot supply
+    // observed module names or relationships.
+    void cause;
+    return {
+      relationships: [],
+      parse_failures: [
+        {
+          path,
+          parser: "utf-8",
+          reason:
+            "Source bytes are not valid UTF-8; import targets were not parsed.",
+        },
+      ],
+    };
+  }
   const { ast, reasons } = parseWithBabel(path, source, language);
   const parseFailures = reasons.map((reason) => ({
     path,
diff --git a/tests/boundary/cli/referenceSourceUtf8.test.ts b/tests/boundary/cli/referenceSourceUtf8.test.ts
new file mode 100644
index 000000000..06093f427
--- /dev/null
+++ b/tests/boundary/cli/referenceSourceUtf8.test.ts
@@ -0,0 +1,77 @@
+import { createHash } from "node:crypto";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect } from "vitest";
+
+import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+cliTest(
+  "retains malformed source bytes without inventing decoded import targets",
+  async ({ cli }) => {
+    const root = await createTestTempDirectory("rea-reference-utf8-");
+    const sources = new Map([
+      [
+        "invalid.mjs",
+        Buffer.concat([
+          Buffer.from('import "./caf'),
+          Buffer.from([0xff]),
+          Buffer.from('.js";\n'),
+        ]),
+      ],
+      [
+        "comment.ts",
+        Buffer.concat([
+          Buffer.from('import "./dep.js"; // '),
+          Buffer.from([0xc0, 0xaf]),
+        ]),
+      ],
+      ["valid.mjs", Buffer.from('import "./caf�.js";\n')],
+      ["caf�.js", Buffer.from("export const value = 1;\n")],
+      ["dep.js", Buffer.from("export const value = 2;\n")],
+    ]);
+    await Promise.all(
+      [...sources].map(([path, bytes]) => writeFile(join(root, path), bytes)),
+    );
+    const result = await cli.run({
+      arguments: ["import-reference-source", root, "--json"],
+      environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
+    });
+    expect(result.exitCode).toBe(0);
+    const graph = historicalSourceGraphSchema.parse(result.json);
+    expect(graph.parse_failures).toEqual([
+      {
+        path: "comment.ts",
+        parser: "utf-8",
+        reason:
+          "Source bytes are not valid UTF-8; import targets were not parsed.",
+      },
+      {
+        path: "invalid.mjs",
+        parser: "utf-8",
+        reason:
+          "Source bytes are not valid UTF-8; import targets were not parsed.",
+      },
+    ]);
+    expect(graph.relationships).toEqual([
+      {
+        from_path: "valid.mjs",
+        to: "caf�.js",
+        kind: "imports",
+        resolution: "internal",
+        parse_state: "parsed",
+      },
+    ]);
+    for (const [path, bytes] of sources)
+      expect(graph.entries).toContainEqual(
+        expect.objectContaining({
+          path,
+          sha256: createHash("sha256").update(bytes).digest("hex"),
+          size: bytes.length,
+          content_state: "hashed",
+        }),
+      );
+  },
+);

From 82bbe743336244d398e67512659ea6943d43a4a4 Mon Sep 17 00:00:00 2001
From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
Date: Fri, 9 Oct 2026 11:54:27 -0400
Subject: [PATCH 033/189] fix(browser): follow only HTTP redirect statuses for
 source maps

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
---
 src/browser/WebSourceMapFetcher.ts            |  4 +-
 .../browser/webSourceMapHttpStatus.test.ts    | 89 +++++++++++++++++++
 2 files changed, 92 insertions(+), 1 deletion(-)
 create mode 100644 tests/boundary/browser/webSourceMapHttpStatus.test.ts

diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts
index f5657a77b..546fd9d97 100644
--- a/src/browser/WebSourceMapFetcher.ts
+++ b/src/browser/WebSourceMapFetcher.ts
@@ -289,7 +289,9 @@ const fetchFollowingApprovedRedirects = async (
       await response.body?.cancel(signal.reason).catch(() => undefined);
       throw signal.reason;
     }
-    if (response.status < 300 || response.status >= 400)
+    // Location is a redirect target only for the Fetch redirect statuses.
+    // A 304 or another 3xx response must retain its own HTTP failure.
+    if (![301, 302, 303, 307, 308].includes(response.status))
       return { response, fetchedUrl: current };
     const location = response.headers.get("location");
     if (location === null) return { response, fetchedUrl: current };
diff --git a/tests/boundary/browser/webSourceMapHttpStatus.test.ts b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
new file mode 100644
index 000000000..c4e78d72e
--- /dev/null
+++ b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
@@ -0,0 +1,89 @@
+import { createServer } from "node:http";
+
+import { expect, it } from "vitest";
+
+import { fetchWebSourceMaps } from "../../../src/browser/WebSourceMapFetcher.js";
+import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
+
+it("follows only HTTP redirect statuses when a source-map response carries Location", async () => {
+  const calls: string[] = [];
+  const server = createServer((request, response) => {
+    const path = request.url ?? "";
+    calls.push(path);
+    if (path === "/delivered.map") {
+      response.writeHead(200, { "content-type": "application/json" }).end(
+        JSON.stringify({
+          version: 3,
+          names: [],
+          sources: ["original.js"],
+          mappings: "AAAA",
+        }),
+      );
+      return;
+    }
+    response
+      .writeHead(Number(path.slice(1)), { location: "/delivered.map" })
+      .end();
+  });
+  try {
+    await new Promise((resolve, reject) => {
+      server.once("error", reject);
+      server.listen(0, "127.0.0.1", resolve);
+    });
+    const address = server.address();
+    if (address === null || typeof address === "string")
+      throw new TypeError("Expected TCP listener");
+    const origin = `http://127.0.0.1:${String(address.port)}`;
+    const input = analyzeWebBundleInputSchema.parse({
+      cdp_endpoint: "http://127.0.0.1:9222",
+      target_id: "selected-page",
+      allowed_origins: [origin],
+      fetch_source_maps: true,
+    });
+    const failures: unknown[] = [];
+    for (const status of [300, 304, 305, 306, 301, 302, 303, 307, 308]) {
+      calls.length = 0;
+      const url = `${origin}/${String(status)}`;
+      const result = await fetchWebSourceMaps(
+        [
+          {
+            scriptKey: `scr_${"1".repeat(64)}`,
+            declaredUrl: url,
+            fetchUrl: url,
+          },
+        ],
+        input,
+      );
+      const redirect = [301, 302, 303, 307, 308].includes(status);
+      try {
+        expect([...calls]).toEqual(
+          redirect
+            ? [`/${String(status)}`, "/delivered.map"]
+            : [`/${String(status)}`],
+        );
+        expect(result.items[0]?.status).toBe(
+          redirect ? "included" : "fetch_failed",
+        );
+        if (!redirect)
+          expect(result.items[0]?.limitation).toBe(
+            `Source-map server returned HTTP ${String(status)}.`,
+          );
+      } catch (cause) {
+        failures.push(cause);
+      }
+    }
+    if (failures.length > 0)
+      throw new AggregateError(
+        failures,
+        "Nonredirect source-map responses were followed",
+      );
+  } finally {
+    server.closeAllConnections();
+    if (server.listening)
+      await new Promise((resolve, reject) =>
+        server.close((error) =>
+          error === undefined ? resolve() : reject(error),
+        ),
+      );
+  }
+});

From 9367dc13bd8d2732d36d5376b5de170c9f4af424 Mon Sep 17 00:00:00 2001
From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
Date: Fri, 9 Oct 2026 12:12:08 -0400
Subject: [PATCH 034/189] test(browser): avoid duplicating source-map listener
 setup

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
---
 tests/boundary/browser/webSourceMapHttpStatus.test.ts | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/tests/boundary/browser/webSourceMapHttpStatus.test.ts b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
index c4e78d72e..2b229e76d 100644
--- a/tests/boundary/browser/webSourceMapHttpStatus.test.ts
+++ b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
@@ -1,3 +1,4 @@
+import { once } from "node:events";
 import { createServer } from "node:http";
 
 import { expect, it } from "vitest";
@@ -26,10 +27,9 @@ it("follows only HTTP redirect statuses when a source-map response carries Locat
       .end();
   });
   try {
-    await new Promise((resolve, reject) => {
-      server.once("error", reject);
-      server.listen(0, "127.0.0.1", resolve);
-    });
+    const listening = once(server, "listening");
+    server.listen(0, "127.0.0.1");
+    await listening;
     const address = server.address();
     if (address === null || typeof address === "string")
       throw new TypeError("Expected TCP listener");

From 2b4abbf1ccb6dd6ad1248cf48e381df0842542c1 Mon Sep 17 00:00:00 2001
From: AC 
Date: Sat, 10 Oct 2026 00:43:33 +0800
Subject: [PATCH 035/189] fix(javascript): distinguish prefix-only builtins
 from packages

---
 .../JavaScriptArtifactPathResolution.ts       | 11 +---
 .../JavaScriptModuleSpecifierPaths.test.ts    | 66 +++++++++++++++++++
 2 files changed, 68 insertions(+), 9 deletions(-)

diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts
index bb93419d7..90c79b20a 100644
--- a/src/application/javascript/JavaScriptArtifactPathResolution.ts
+++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts
@@ -1,4 +1,4 @@
-import { builtinModules } from "node:module";
+import { isBuiltin } from "node:module";
 import { posix } from "node:path";
 
 import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -63,9 +63,6 @@ const EXTENSIONS = [
   ".html",
   ".node",
 ];
-const NODE_BUILTINS = new Set(
-  builtinModules.map((name) => name.replace(/^node:/u, "")),
-);
 
 type CandidateResolution =
   | {
@@ -194,11 +191,7 @@ const bareModuleCandidate = (
   declared: string,
 ): string | ArtifactPathResolution => {
   const packageName = barePackageName(declared);
-  if (
-    packageName === null ||
-    NODE_BUILTINS.has(packageName) ||
-    declared.startsWith("#")
-  )
+  if (packageName === null || isBuiltin(declared) || declared.startsWith("#"))
     return unresolvedOutcome(input, "external", [
       "The bare specifier is a Node builtin, package import map, or invalid package name.",
     ]);
diff --git a/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts b/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts
index 937773000..a31b2a2ca 100644
--- a/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts
+++ b/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts
@@ -27,6 +27,72 @@ const filesFor = (paths: readonly string[]) =>
     ]),
   );
 
+describe("prefix-only Node builtins", () => {
+  it.each(["import", "require"] as const)(
+    "resolves ordinary packages named test, sqlite and sea for %s",
+    async (moduleKind) => {
+      const root = await createTestTempDirectory("rea-prefix-only-builtins-");
+      const names = ["test", "sqlite", "sea"];
+      for (const name of [...names, "fs"]) {
+        const directory = join(root, "node_modules", name);
+        await mkdir(directory, { recursive: true });
+        await writeFile(
+          join(directory, "index.js"),
+          `module.exports = ${JSON.stringify(name)};`,
+        );
+      }
+      const main = join(
+        root,
+        moduleKind === "import" ? "main.mjs" : "main.cjs",
+      );
+      await writeFile(
+        main,
+        names
+          .map((name, index) =>
+            moduleKind === "import"
+              ? `import value${index} from ${JSON.stringify(name)}; console.log(value${index});`
+              : `console.log(require(${JSON.stringify(name)}));`,
+          )
+          .join("\n") +
+          (moduleKind === "import"
+            ? '\nimport "fs"; import "node:test";'
+            : '\nrequire("fs"); require("node:test");'),
+      );
+      const native = await promisify(execFile)(process.execPath, [main], {
+        timeout: 5_000,
+      });
+      expect(native.stdout.trim().split("\n").slice(0, 3)).toEqual(names);
+      const result = await analyzeJavaScriptApplication({
+        input_path: root,
+        format: "directory",
+      });
+      if (!result.ok) throw result.error;
+      const { graph } = javascriptApplicationAnalysisResultSchema.parse(
+        result.value.normalized_result,
+      );
+      const imports = graph.edges.filter((edge) => edge.relation === "imports");
+      for (const name of names) {
+        const matches = imports.filter(
+          (edge) => edge.properties.specifier === name,
+        );
+        expect(matches.length).toBeGreaterThan(0);
+        for (const edge of matches)
+          expect(edge.properties.resolved_path).toBe(
+            `node_modules/${name}/index.js`,
+          );
+      }
+      for (const name of ["fs", "node:test"]) {
+        const matches = imports.filter(
+          (edge) => edge.properties.specifier === name,
+        );
+        expect(matches.length).toBeGreaterThan(0);
+        for (const edge of matches)
+          expect(edge.properties.resolved_path).toBeNull();
+      }
+    },
+  );
+});
+
 describe("module specifier punctuation", () => {
   it.each(["#", "?"])(
     "keeps CommonJS punctuation and strips URL suffixes for ESM (%s)",

From 7a4f2685d41b134507331c322f0f5da8e1f6c3f4 Mon Sep 17 00:00:00 2001
From: AC 
Date: Sat, 10 Oct 2026 00:44:29 +0800
Subject: [PATCH 036/189] fix(javascript): reject invalid package exports
 configurations

---
 .../JavaScriptArtifactPathResolution.ts       | 27 ++++++++++++--
 .../packageConditionalExports.test.ts         | 36 +++++++++++++++++++
 2 files changed, 61 insertions(+), 2 deletions(-)

diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts
index 90c79b20a..b5ba5847b 100644
--- a/src/application/javascript/JavaScriptArtifactPathResolution.ts
+++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts
@@ -496,12 +496,24 @@ const packageExport = (
   value: unknown,
   moduleKind: ResolveArtifactPathInput["moduleKind"],
 ): PackageExportOutcome => {
+  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
+    const keys = Object.keys(value);
+    if (
+      keys.some((key) => key.startsWith(".")) &&
+      keys.some((key) => !key.startsWith("."))
+    )
+      return {
+        status: "rejected",
+        limitation:
+          "The package exports configuration mixes subpath keys and condition keys.",
+      };
+  }
   const root =
     typeof value === "object" && value !== null && Object.hasOwn(value, ".")
       ? Reflect.get(value, ".")
       : value;
   const flattened = exportTargets(root, packageExportConditions(moduleKind));
-  if (flattened.kind === "invalid")
+  if (flattened.kind === "invalid" || flattened.kind === "invalid-config")
     return { status: "rejected", limitation: flattened.limitation };
   const first =
     flattened.kind === "unmatched" ? undefined : flattened.values[0];
@@ -517,7 +529,8 @@ const packageExport = (
 type ExportTargets =
   | { readonly kind: "targets"; readonly values: readonly string[] }
   | { readonly kind: "unmatched" }
-  | { readonly kind: "invalid"; readonly limitation: string };
+  | { readonly kind: "invalid"; readonly limitation: string }
+  | { readonly kind: "invalid-config"; readonly limitation: string };
 
 const invalidExportTarget = (
   value: unknown,
@@ -570,6 +583,8 @@ const exportTargets = (
     let invalid: string | null = null;
     for (const entry of value) {
       const nested = exportTargets(entry, conditions);
+      // Node's array fallback catches invalid targets, not invalid configuration.
+      if (nested.kind === "invalid-config") return nested;
       if (nested.kind === "invalid") {
         invalid = nested.limitation;
         continue;
@@ -587,6 +602,14 @@ const exportTargets = (
       value,
       "must be a relative string, object, array, or null",
     );
+  for (const key of Object.keys(value)) {
+    const numeric = Number(key);
+    if (String(numeric) === key && numeric >= 0 && numeric < 0xffff_ffff)
+      return {
+        kind: "invalid-config",
+        limitation: `The package exports configuration contains numeric condition key ${JSON.stringify(key)}.`,
+      };
+  }
   for (const [condition, target] of Object.entries(value)) {
     if (!conditions.has(condition)) continue;
     const nested = exportTargets(target, conditions);
diff --git a/tests/boundary/javascript/packageConditionalExports.test.ts b/tests/boundary/javascript/packageConditionalExports.test.ts
index 7c65b6d49..190fa0b4e 100644
--- a/tests/boundary/javascript/packageConditionalExports.test.ts
+++ b/tests/boundary/javascript/packageConditionalExports.test.ts
@@ -122,6 +122,42 @@ const expectNodeAgreement = async (
   return outcome;
 };
 describe("ordered package exports conditions", () => {
+  it.each([
+    { ".": "./default.cjs", import: "./specific.cjs" },
+    { default: "./default.cjs", "./feature": "./specific.cjs" },
+    { "0": "./specific.cjs", default: "./default.cjs" },
+    { ".": { "1.5": "./specific.cjs", default: "./default.cjs" } },
+    { node: [{ "4294967294": null }, "./array.cjs"], default: "./default.cjs" },
+  ])(
+    "rejects invalid exports configuration %j without fallback",
+    async (exportsMap) => {
+      for (const moduleKind of ["import", "require"] as const) {
+        const { node, node_error, outcome } = await compareWithNode(
+          exportsMap,
+          moduleKind,
+        );
+        expect(node).toBeNull();
+        expect(node_error).toBe("ERR_INVALID_PACKAGE_CONFIG");
+        expect(outcome).toMatchObject({
+          resolved_path: null,
+          resolution_status: "rejected",
+        });
+        expect(outcome.limitations[0]).toContain("exports configuration");
+      }
+    },
+  );
+
+  it.each([
+    { "01": "./specific.cjs", default: "./default.cjs" },
+    { "4294967295": "./specific.cjs", default: "./default.cjs" },
+    { browser: { "0": null }, default: "./default.cjs" },
+    ["./default.cjs", { "0": null }],
+    { ".": "./default.cjs", "./feature": "./specific.cjs" },
+  ])("preserves valid or unvisited conditions in %j", async (exportsMap) => {
+    for (const moduleKind of ["import", "require"] as const)
+      await expectNodeAgreement(exportsMap, "default.cjs", moduleKind);
+  });
+
   it.each(["import", "require"] as const)(
     "matches Node when default precedes %s",
     async (moduleKind) => {

From cfb12e47dc241f057be93a00892f7d7361d6119d Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:39:11 +0800
Subject: [PATCH 037/189] fix(artifacts): validate only active extraction
 entries

---
 .../extraction/ArtifactExtraction.ts          | 38 +++++++--------
 ...actProvider.extractionCompleteness.test.ts | 46 ++++++++++++++++++-
 2 files changed, 64 insertions(+), 20 deletions(-)

diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts
index 9bfdd13b4..8e40d6cc5 100644
--- a/src/artifacts/extraction/ArtifactExtraction.ts
+++ b/src/artifacts/extraction/ArtifactExtraction.ts
@@ -54,12 +54,26 @@ export const extractArtifact = async (
       (occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
       occurrence.logical_path !== ".",
   );
-  const selectedIds = new Set(
-    selectedOccurrences.map(({ occurrence_id: id }) => id),
-  );
   const regularPaths = new Set(
     selectedOccurrences.map(({ logical_path: path }) => path),
   );
+  const activeOccurrences = selectedOccurrences.filter(({ logical_path }) => {
+    // Nested members remain represented by their containing regular file;
+    // only entries exposed by the active reader are materialized.
+    let path = logical_path;
+    for (
+      let slash = path.lastIndexOf("/");
+      slash >= 0;
+      slash = path.lastIndexOf("/")
+    ) {
+      path = path.slice(0, slash);
+      if (regularPaths.has(path)) return false;
+    }
+    return true;
+  });
+  const selectedIds = new Set(
+    activeOccurrences.map(({ occurrence_id: id }) => id),
+  );
   const occurrences = new Map();
   const neededNodes = new Set();
   collectOccurrences(
@@ -75,7 +89,7 @@ export const extractArtifact = async (
     occurrences,
     nodes,
   };
-  const selected = selectedOccurrences.map((occurrence) => {
+  const selected = activeOccurrences.map((occurrence) => {
     // REA never decrypts archive entries, so an encrypted entry makes the
     // complete extraction unsupported rather than the archive invalid.
     if (occurrence.encrypted)
@@ -101,25 +115,11 @@ export const extractArtifact = async (
       );
     return { occurrence, node };
   });
-  const activeSelected = selected.filter(({ occurrence }) => {
-    // Nested members remain represented by their containing regular file;
-    // only entries exposed by the active reader are materialized.
-    let path = occurrence.logical_path;
-    for (
-      let slash = path.lastIndexOf("/");
-      slash >= 0;
-      slash = path.lastIndexOf("/")
-    ) {
-      path = path.slice(0, slash);
-      if (regularPaths.has(path)) return false;
-    }
-    return true;
-  });
   return materializeSelection({
     input,
     sourcePath,
     inventory,
-    selected: activeSelected,
+    selected,
     signal,
   });
 };
diff --git a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
index 0a160a1da..e5994c79a 100644
--- a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
+++ b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
@@ -1,7 +1,7 @@
 import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
 import { join } from "node:path";
 
-import { createPackage } from "@electron/asar";
+import { createPackage, createPackageWithOptions } from "@electron/asar";
 import { expect, it, onTestFinished, vi } from "vitest";
 
 import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
@@ -92,6 +92,50 @@ it("preserves every equal-content occurrence and copies a nested ASAR as its con
     );
 });
 
+it("ignores unavailable members of a nested ASAR but refuses them as active entries", async () => {
+  const root = await createTestTempDirectory("rea-extract-nested-unpacked-");
+  const contents = join(root, "contents");
+  await mkdir(join(contents, "native"), { recursive: true });
+  await writeFile(join(contents, "main.js"), "export default 1;\n");
+  await writeFile(join(contents, "native", "addon.node"), "native bytes\n");
+
+  const source = join(root, "bundle");
+  await mkdir(source);
+  const archive = join(source, "app.asar");
+  await createPackageWithOptions(contents, archive, { unpack: "**/*.node" });
+  await rm(join(`${archive}.unpacked`, "native", "addon.node"));
+
+  const nestedOutput = join(root, "nested-output");
+  const nestedResult = await extract(source, nestedOutput);
+  if (!nestedResult.ok) throw nestedResult.error;
+  const nestedExtraction = artifactExtractionResultSchema.parse(
+    nestedResult.value.result,
+  );
+  expect(
+    nestedExtraction.extraction_manifest.selected_occurrence_ids,
+  ).toHaveLength(1);
+  expect(
+    nestedExtraction.artifacts.map(({ relative_path }) => relative_path),
+  ).toEqual(["app.asar"]);
+  expect(await readFile(join(nestedOutput, "app.asar"))).toEqual(
+    await readFile(archive),
+  );
+
+  const activeOutput = join(root, "active-output");
+  const activeResult = await extract(archive, activeOutput);
+  if (activeResult.ok)
+    throw new Error("Unavailable active ASAR member must fail extraction");
+  expect(projectAnalysisError(activeResult.error)).toMatchObject({
+    code: "artifact_operation_failed",
+    details: {
+      operation: "extract_artifact",
+      reason: "format",
+      detail: expect.stringContaining("native/addon.node"),
+    },
+  });
+  await expect(access(activeOutput)).rejects.toThrow();
+});
+
 // Synchronize a real filesystem change after the actual inventory scan. The
 // production reader, writes, failure translation and rollback all remain real.
 const afterInventory = (change: () => Promise): void => {

From b628bba1fa65fd3b51363bf4b745f0afc57e1dba Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:39:28 +0800
Subject: [PATCH 038/189] refactor(javascript): normalize erased expression
 syntax once

---
 .../JavaScriptApplicationDeclarations.test.ts |  54 -------
 .../JavaScriptApplicationSatisfies.test.ts    |  57 -------
 .../JavaScriptApplicationTypeScript.test.ts   | 144 ++++++++++++++++++
 src/domain/javascript/javascriptAstValues.ts  |  27 ++++
 .../javascriptSemanticAnalysis.unions.test.ts |  20 +++
 .../javascriptSemanticCallResolution.ts       |  10 +-
 .../javascriptSemanticDataEffectHelpers.ts    |  15 +-
 .../javascriptSemanticDataEffects.ts          |  12 +-
 .../javascriptSemanticMemberMutations.ts      |  17 ++-
 .../javascript/javascriptSemanticObjects.ts   |  15 +-
 .../javascript/javascriptSemanticPromises.ts  |  39 +++--
 .../javascriptSemanticRequireOrigin.ts        |  34 +++--
 .../javascript/javascriptSemanticReturns.ts   |  11 +-
 .../javascript/javascriptSemanticValues.ts    |  36 ++++-
 .../javascript/javascriptSourceParser.ts      |  10 +-
 .../javascriptStaticAnalysisHelpers.ts        |   5 +-
 ...avascriptStaticAnalysisModuleIndex.test.ts |  12 ++
 17 files changed, 313 insertions(+), 205 deletions(-)
 delete mode 100644 src/application/javascript/JavaScriptApplicationDeclarations.test.ts
 delete mode 100644 src/application/javascript/JavaScriptApplicationSatisfies.test.ts
 create mode 100644 src/application/javascript/JavaScriptApplicationTypeScript.test.ts

diff --git a/src/application/javascript/JavaScriptApplicationDeclarations.test.ts b/src/application/javascript/JavaScriptApplicationDeclarations.test.ts
deleted file mode 100644
index 30a80bb62..000000000
--- a/src/application/javascript/JavaScriptApplicationDeclarations.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { writeFile } from "node:fs/promises";
-import { join } from "node:path";
-
-import { expect, it } from "vitest";
-
-import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
-import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
-import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
-import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
-
-it.each(["types.d.ts", "types.d.mts", "types.d.cts"])(
-  "keeps valid ambient declarations complete in %s",
-  async (path) => {
-    const root = await createTestTempDirectory("rea-declaration-file-");
-    const source = "export const value: number;\n";
-    await writeFile(join(root, path), source);
-    const result = await analyzeJavaScriptApplication({
-      input_path: root,
-      format: "directory",
-    });
-    if (!result.ok) throw result.error;
-    const analysis = javascriptApplicationAnalysisResultSchema.parse(
-      result.value.normalized_result,
-    );
-    expect(analysis.graph.coverage.status).toBe("complete");
-    expect(parseJavaScriptSource(source, path)?.errors).toEqual([]);
-  },
-);
-
-it("retains the missing-initializer diagnostic for ordinary TypeScript", () => {
-  const errors = parseJavaScriptSource(
-    "export const value: number;",
-    "types.ts",
-  )?.errors;
-  expect(errors?.map(({ message }) => message)).toContain(
-    "Missing initializer in const declaration. (1:26)",
-  );
-});
-
-it("keeps CommonJS TypeScript angle-bracket assertions complete", async () => {
-  const root = await createTestTempDirectory("rea-cts-assertion-");
-  const source = "export const value = 42;\n";
-  await writeFile(join(root, "app.cts"), source);
-  const result = await analyzeJavaScriptApplication({
-    input_path: root,
-    format: "directory",
-  });
-  if (!result.ok) throw result.error;
-  const analysis = javascriptApplicationAnalysisResultSchema.parse(
-    result.value.normalized_result,
-  );
-  expect(analysis.graph.coverage.status).toBe("complete");
-  expect(parseJavaScriptSource(source, "app.cts")?.errors).toEqual([]);
-});
diff --git a/src/application/javascript/JavaScriptApplicationSatisfies.test.ts b/src/application/javascript/JavaScriptApplicationSatisfies.test.ts
deleted file mode 100644
index 8507180f1..000000000
--- a/src/application/javascript/JavaScriptApplicationSatisfies.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { writeFile } from "node:fs/promises";
-import { join } from "node:path";
-
-import { expect, it } from "vitest";
-
-import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
-import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
-import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
-import { topLevelBinding } from "../../domain/javascript/javascriptSemanticAnalysis.fixture.js";
-import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
-
-it.each([
-  '"ready" satisfies string',
-  '("ready" satisfies string) as string',
-  '("ready" satisfies string)!',
-])("retains the runtime primitive through %s", (expression) => {
-  const ir = analyzeJavaScriptSemantics(`const value = ${expression};`);
-  expect(topLevelBinding(ir, "value").value).toEqual({
-    status: "literal",
-    value: "ready",
-  });
-});
-
-it("retains exported constant evidence through a type-only satisfies expression", async () => {
-  const root = await createTestTempDirectory("rea-ts-satisfies-");
-  await writeFile(
-    join(root, "app.ts"),
-    'export const value = "ready" satisfies string;\n',
-  );
-  const result = await analyzeJavaScriptApplication({
-    input_path: root,
-    format: "directory",
-  });
-  if (!result.ok) throw result.error;
-  const analysis = javascriptApplicationAnalysisResultSchema.parse(
-    result.value.normalized_result,
-  );
-  expect(
-    analysis.semantic_graph.nodes.filter(
-      ({ kind, properties }) =>
-        kind === "literal" && properties.value === "ready",
-    ),
-  ).toHaveLength(1);
-});
-
-it("retains local call targets and exported callable links through satisfies", () => {
-  const ir = analyzeJavaScriptSemantics(
-    'export const render = (() => "ready") satisfies (() => string); render();',
-  );
-  const callable = ir.callables[0];
-  if (callable === undefined) throw new Error("Missing callable");
-  expect(
-    ir.moduleLinks.find(({ localName }) => localName === "render")?.callableId,
-  ).toBe(callable.callableId);
-  expect(ir.callSites[0]?.calleeCallableIds).toEqual([callable.callableId]);
-  expect(ir.callSites[0]?.resolution).toBe("exact");
-});
diff --git a/src/application/javascript/JavaScriptApplicationTypeScript.test.ts b/src/application/javascript/JavaScriptApplicationTypeScript.test.ts
new file mode 100644
index 000000000..6d59578e7
--- /dev/null
+++ b/src/application/javascript/JavaScriptApplicationTypeScript.test.ts
@@ -0,0 +1,144 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { canonicalJson } from "../../domain/comparisonSemantics.js";
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceParser.js";
+import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
+
+type ApplicationAnalysis = ReturnType<
+  typeof javascriptApplicationAnalysisResultSchema.parse
+>;
+
+const analyzeFiles = async (
+  files: ReadonlyMap,
+): Promise => {
+  const root = await createTestTempDirectory("rea-typescript-application-");
+  await Promise.all(
+    [...files].map(([path, source]) => writeFile(join(root, path), source)),
+  );
+  const result = await analyzeJavaScriptApplication({
+    input_path: root,
+    format: "directory",
+  });
+  if (!result.ok) throw result.error;
+  const analysis = javascriptApplicationAnalysisResultSchema.parse(
+    result.value.normalized_result,
+  );
+  return javascriptApplicationAnalysisResultSchema.parse(
+    JSON.parse(canonicalJson(analysis, "TypeScript application analysis")),
+  );
+};
+
+it.each(["types.d.ts", "types.d.mts", "types.d.cts"])(
+  "keeps valid ambient declarations complete in %s",
+  async (path) => {
+    const source = "export const value: number;\n";
+    const analysis = await analyzeFiles(new Map([[path, source]]));
+
+    expect(analysis.graph.coverage.status).toBe("complete");
+    expect(parseJavaScriptSource(source, path)?.errors).toEqual([]);
+  },
+);
+
+it("retains the missing-initializer diagnostic for ordinary TypeScript", () => {
+  const errors = parseJavaScriptSource(
+    "export const value: number;",
+    "types.ts",
+  )?.errors;
+  expect(errors?.map(({ message }) => message)).toContain(
+    "Missing initializer in const declaration. (1:26)",
+  );
+});
+
+it("keeps CommonJS TypeScript angle-bracket assertions complete", async () => {
+  const source = "export const value = 42;\n";
+  const analysis = await analyzeFiles(new Map([["app.cts", source]]));
+
+  expect(analysis.graph.coverage.status).toBe("complete");
+  expect(parseJavaScriptSource(source, "app.cts")?.errors).toEqual([]);
+});
+
+it("retains exported constant evidence through a type-only satisfies expression", async () => {
+  const analysis = await analyzeFiles(
+    new Map([["app.ts", 'export const value = "ready" satisfies string;\n']]),
+  );
+
+  expect(
+    analysis.semantic_graph.nodes.filter(
+      ({ kind, properties }) =>
+        kind === "literal" && properties.value === "ready",
+    ),
+  ).toHaveLength(1);
+});
+
+it("resolves erased wrappers through the composed application graph", async () => {
+  const source = `
+    const dependency = require("./dependency.ts")["value" as const] satisfies number;
+    export { dependency };
+    function render() { return "ready"; }
+    export const specialized = render satisfies () => string;
+    specialized();
+  `;
+  const analysis = await analyzeFiles(
+    new Map([
+      ["app.mts", source],
+      ["dependency.ts", "export const value = 1;\n"],
+    ]),
+  );
+
+  expect(analysis.graph.edges).toContainEqual(
+    expect.objectContaining({
+      relation: "imports",
+      properties: expect.objectContaining({
+        specifier: "./dependency.ts",
+        imported_path: ["value"],
+        resolved_path: "dependency.ts",
+        resolution_status: "resolved",
+      }),
+    }),
+  );
+  expect(analysis.semantic_graph.relations).toContainEqual(
+    expect.objectContaining({ relation: "calls", resolution: "resolved" }),
+  );
+  expect(
+    analysis.graph.nodes.flatMap(({ observations }) => observations),
+  ).toContainEqual(
+    expect.objectContaining({
+      properties: expect.objectContaining({
+        semantic_role: "export-return-shapes",
+        exported_name: "specialized",
+        static_return_shapes: expect.arrayContaining([
+          expect.objectContaining({
+            value_status: "literal",
+            fields: expect.arrayContaining([
+              expect.objectContaining({ path: "", value: "ready" }),
+            ]),
+          }),
+        ]),
+      }),
+    }),
+  );
+  expect(parseJavaScriptSource(source, "app.mts")?.errors).toEqual([]);
+});
+
+it("applies TypeScript .mts ambiguity rules while retaining unambiguous generics", () => {
+  expect(
+    parseJavaScriptSource(
+      "export const identity = (value: T) => value;",
+      "app.mts",
+    )?.errors,
+  ).toEqual([]);
+  expect(
+    parseJavaScriptSource(
+      "export const identity = (value: T) => value;",
+      "app.mts",
+    )?.errors.map(({ reasonCode }) => reasonCode),
+  ).toContain("ReservedArrowTypeParam");
+  expect(parseJavaScriptSource("const value = ;", "app.mts")).toBe(
+    null,
+  );
+});
diff --git a/src/domain/javascript/javascriptAstValues.ts b/src/domain/javascript/javascriptAstValues.ts
index b7f8d0efc..f0a0528c0 100644
--- a/src/domain/javascript/javascriptAstValues.ts
+++ b/src/domain/javascript/javascriptAstValues.ts
@@ -1,12 +1,38 @@
 import * as t from "@babel/types";
 import type { JavaScriptSemanticPrimitive } from "./javascriptSemanticValueTypes.js";
 
+/**
+ * Remove wrappers that affect TypeScript or Flow checking but not runtime
+ * expression identity. The returned depth lets bounded evaluators account for
+ * syntax that normalization would otherwise skip.
+ */
+export const unwrapJavaScriptExpression = (
+  node: t.Node,
+): { readonly node: t.Node; readonly depth: number } => {
+  let current = node;
+  let depth = 0;
+  while (
+    t.isParenthesizedExpression(current) ||
+    t.isTSAsExpression(current) ||
+    t.isTSTypeAssertion(current) ||
+    t.isTSNonNullExpression(current) ||
+    t.isTSSatisfiesExpression(current) ||
+    t.isTSInstantiationExpression(current) ||
+    t.isTypeCastExpression(current)
+  ) {
+    current = current.expression;
+    depth += 1;
+  }
+  return { node: current, depth };
+};
+
 /** Read one syntax-level primitive only when its value is exact. */
 export const readExactJavaScriptLiteral = (
   node: t.Node,
 ):
   | { readonly found: true; readonly value: JavaScriptSemanticPrimitive }
   | { readonly found: false } => {
+  node = unwrapJavaScriptExpression(node).node;
   if (t.isStringLiteral(node)) return { found: true, value: node.value };
   if (t.isNumericLiteral(node) && Number.isFinite(node.value))
     return { found: true, value: node.value };
@@ -44,6 +70,7 @@ export const semanticStaticPropertyKey = (
   property: t.Node,
   computed: boolean,
 ): string | null => {
+  property = unwrapJavaScriptExpression(property).node;
   if (t.isStringLiteral(property) || t.isNumericLiteral(property))
     return String(property.value);
   return !computed && t.isIdentifier(property) ? property.name : null;
diff --git a/src/domain/javascript/javascriptSemanticAnalysis.unions.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.unions.test.ts
index 24bbb1707..9e02cdb00 100644
--- a/src/domain/javascript/javascriptSemanticAnalysis.unions.test.ts
+++ b/src/domain/javascript/javascriptSemanticAnalysis.unions.test.ts
@@ -390,6 +390,26 @@ describe("semantic expression depth bounds", () => {
     });
   });
 
+  it("counts erased TypeScript wrappers against expression depth", () => {
+    const parsed = parseJavaScriptSource("const answer = true;");
+    const declaration = parsed?.program.body[0];
+    const declarator = t.isVariableDeclaration(declaration)
+      ? declaration.declarations[0]
+      : undefined;
+    if (parsed === null || !t.isVariableDeclarator(declarator))
+      throw new Error("Expected parsed binding initializer");
+    let expression: t.Expression = t.booleanLiteral(true);
+    for (let index = 0; index < 300; index += 1)
+      expression = t.tsAsExpression(expression, t.tsStringKeyword());
+    declarator.init = expression;
+
+    const ir = analyzeParsedJavaScriptSemantics(parsed);
+    expect(topLevelBinding(ir, "answer").value).toMatchObject({
+      status: "unknown",
+      resourceLimit: "expression-depth",
+    });
+  });
+
   it("preserves exact shallow addition alternatives", () => {
     expect(valueOf('(choice ? "a" : "b") + (other ? "1" : "2")')).toEqual({
       status: "union",
diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts
index 24673279a..08453a651 100644
--- a/src/domain/javascript/javascriptSemanticCallResolution.ts
+++ b/src/domain/javascript/javascriptSemanticCallResolution.ts
@@ -6,6 +6,7 @@ import type {
 } from "./javascriptSemanticIr.js";
 import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
+import { unwrapJavaScriptExpression } from "./javascriptAstValues.js";
 import {
   resolveSemanticBindingState,
   type JavaScriptSemanticAnalysisState,
@@ -51,6 +52,8 @@ const resolveCallables = (
   node: t.Node,
   context: CallResolutionContext,
 ): LocalCallableResolution => {
+  const unwrapped = unwrapJavaScriptExpression(node).node;
+  if (unwrapped !== node) return resolveCallables(unwrapped, context);
   const direct = semanticCallableIdForNode(node);
   if (direct !== null && context.callableById.has(direct))
     return {
@@ -59,13 +62,6 @@ const resolveCallables = (
       reason: "Direct local callable.",
     };
   if (t.isIdentifier(node)) return resolveIdentifier(node, context);
-  if (
-    t.isTSAsExpression(node) ||
-    t.isTSTypeAssertion(node) ||
-    t.isTSNonNullExpression(node) ||
-    t.isTSSatisfiesExpression(node)
-  )
-    return resolveCallables(node.expression, context);
   if (t.isConditionalExpression(node) || t.isLogicalExpression(node))
     return resolveAlternatives(
       t.isConditionalExpression(node) ? node.consequent : node.left,
diff --git a/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts b/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts
index f98b791dc..5485fcde9 100644
--- a/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts
+++ b/src/domain/javascript/javascriptSemanticDataEffectHelpers.ts
@@ -14,6 +14,7 @@ import {
   readExactJavaScriptLiteral,
   semanticStaticPropertyKey,
   semanticStaticPropertyName,
+  unwrapJavaScriptExpression,
 } from "./javascriptAstValues.js";
 
 export interface SemanticProjectedBinding {
@@ -56,15 +57,11 @@ const assignedSourceIs = (node: t.Node, source: t.Node): boolean => {
   let value = source;
   while (true) {
     if (t.isAwaitExpression(value)) value = value.argument;
-    else if (
-      t.isParenthesizedExpression(value) ||
-      t.isTSAsExpression(value) ||
-      t.isTSTypeAssertion(value) ||
-      t.isTypeCastExpression(value) ||
-      t.isTSSatisfiesExpression(value)
-    )
-      value = value.expression;
-    else break;
+    else {
+      const unwrapped = unwrapJavaScriptExpression(value).node;
+      if (unwrapped === value) break;
+      value = unwrapped;
+    }
   }
   return value === node;
 };
diff --git a/src/domain/javascript/javascriptSemanticDataEffects.ts b/src/domain/javascript/javascriptSemanticDataEffects.ts
index 83afd13d7..445cd2e5e 100644
--- a/src/domain/javascript/javascriptSemanticDataEffects.ts
+++ b/src/domain/javascript/javascriptSemanticDataEffects.ts
@@ -12,6 +12,7 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 import {
   semanticStaticPropertyKey,
   semanticStaticPropertyName,
+  unwrapJavaScriptExpression,
 } from "./javascriptAstValues.js";
 import {
   resolveSemanticBindingState,
@@ -178,16 +179,7 @@ const collectDefaults = (
       (node.operator !== "??" && node.operator !== "||")
     )
       return;
-    let source = node.left;
-    while (
-      t.isParenthesizedExpression(source) ||
-      t.isTSAsExpression(source) ||
-      t.isTSTypeAssertion(source) ||
-      t.isTypeCastExpression(source) ||
-      t.isTSSatisfiesExpression(source) ||
-      t.isTSNonNullExpression(source)
-    )
-      source = source.expression;
+    const source = unwrapJavaScriptExpression(node.left).node;
     const candidate = configurationsByNode.get(source);
     if (candidate === undefined) return;
     output.push({
diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts
index 622d9f630..0d3a00f22 100644
--- a/src/domain/javascript/javascriptSemanticMemberMutations.ts
+++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts
@@ -7,7 +7,10 @@ import {
 } from "./javascriptSemanticState.js";
 import { evaluateSemanticBinding } from "./javascriptSemanticValues.js";
 import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
-import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
+import {
+  semanticStaticPropertyKey,
+  unwrapJavaScriptExpression,
+} from "./javascriptAstValues.js";
 
 type PropertyPath = readonly (string | number | null)[];
 
@@ -28,6 +31,11 @@ export const collectSemanticMemberMutations = (
     bindings: ReadonlySet,
     mutation: t.Node,
   ): void => {
+    const unwrapped = unwrapJavaScriptExpression(node).node;
+    if (unwrapped !== node) {
+      markValue(unwrapped, path, bindings, mutation);
+      return;
+    }
     if (t.isIdentifier(node)) {
       const binding = resolveSemanticBindingState(state, node, node.name);
       if (binding === undefined || bindings.has(binding.bindingId)) return;
@@ -224,13 +232,6 @@ const referencedValues = (
         : [];
     });
   }
-  if (
-    t.isTSAsExpression(node) ||
-    t.isTSTypeAssertion(node) ||
-    t.isTSSatisfiesExpression(node) ||
-    t.isTSNonNullExpression(node)
-  )
-    return [{ node: node.expression, path }];
   if (t.isConditionalExpression(node))
     return [
       { node: node.consequent, path },
diff --git a/src/domain/javascript/javascriptSemanticObjects.ts b/src/domain/javascript/javascriptSemanticObjects.ts
index a7872efb0..27f5d73b3 100644
--- a/src/domain/javascript/javascriptSemanticObjects.ts
+++ b/src/domain/javascript/javascriptSemanticObjects.ts
@@ -8,7 +8,10 @@ import {
   semanticCallableIdForNode,
   semanticReadsBeforeWrite,
 } from "./javascriptSemanticProjection.js";
-import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
+import {
+  semanticStaticPropertyKey,
+  unwrapJavaScriptExpression,
+} from "./javascriptAstValues.js";
 import {
   resolveSemanticBindingState,
   type JavaScriptSemanticAnalysisState,
@@ -205,6 +208,7 @@ const expressionObjectIdentity = (
   let current = node;
   let staticPath = true;
   while (current !== null && current !== undefined) {
+    current = unwrapJavaScriptExpression(current).node;
     if (
       t.isMemberExpression(current) ||
       t.isOptionalMemberExpression(current)
@@ -216,14 +220,7 @@ const expressionObjectIdentity = (
       if (name === null) staticPath = false;
       else path.push(name);
       current = current.object;
-    } else if (
-      t.isTSAsExpression(current) ||
-      t.isTSTypeAssertion(current) ||
-      t.isTSNonNullExpression(current) ||
-      t.isTSSatisfiesExpression(current)
-    )
-      current = current.expression;
-    else break;
+    } else break;
   }
   return {
     bindingId: t.isIdentifier(current)
diff --git a/src/domain/javascript/javascriptSemanticPromises.ts b/src/domain/javascript/javascriptSemanticPromises.ts
index d956d68f7..524d3d0ff 100644
--- a/src/domain/javascript/javascriptSemanticPromises.ts
+++ b/src/domain/javascript/javascriptSemanticPromises.ts
@@ -5,7 +5,10 @@ import type {
   JavaScriptSemanticPromiseOperation,
 } from "./javascriptSemanticIr.js";
 import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
-import { semanticStaticPropertyName } from "./javascriptAstValues.js";
+import {
+  semanticStaticPropertyName,
+  unwrapJavaScriptExpression,
+} from "./javascriptAstValues.js";
 import {
   resolveSemanticBindingState,
   semanticResolutionBlocked,
@@ -173,7 +176,9 @@ const isUnshadowedGlobalPromise = (
 const isPromiseProducer = (
   node: t.Node,
   state: JavaScriptSemanticAnalysisState,
-): boolean => promiseCandidateDetails(unwrapExpression(node), state) !== null;
+): boolean =>
+  promiseCandidateDetails(unwrapJavaScriptExpression(node).node, state) !==
+  null;
 
 const semanticPromiseId = (kind: PromiseKind, node: t.Node): string =>
   `promise:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
@@ -207,7 +212,7 @@ const ownershipAtAncestor = (
 ): PromiseOwnership | "boundary" | null => {
   const { candidate, candidateByNode, state, returnSiteIdFor } = context;
   if (t.isAwaitExpression(ancestor))
-    return unwrapExpression(ancestor.argument) === candidate.node
+    return unwrapJavaScriptExpression(ancestor.argument).node === candidate.node
       ? emptyOwnership("awaited")
       : "boundary";
   const outer = candidateByNode.get(ancestor);
@@ -230,7 +235,7 @@ const ownershipAtAncestor = (
   if (t.isReturnStatement(ancestor)) {
     if (
       ancestor.argument == null ||
-      unwrapExpression(ancestor.argument) !== candidate.node
+      unwrapJavaScriptExpression(ancestor.argument).node !== candidate.node
     )
       return "boundary";
     return returnedPromiseOwnership(
@@ -240,14 +245,15 @@ const ownershipAtAncestor = (
     );
   }
   if (t.isExpressionStatement(ancestor))
-    return unwrapExpression(ancestor.expression) === candidate.node
+    return unwrapJavaScriptExpression(ancestor.expression).node ===
+      candidate.node
       ? emptyOwnership("detached")
       : "boundary";
   const callableId = semanticCallableIdForNode(ancestor);
   if (callableId === null || callableId !== candidate.ownerCallableId)
     return null;
   return t.isArrowFunctionExpression(ancestor) &&
-    unwrapExpression(ancestor.body) === candidate.node
+    unwrapJavaScriptExpression(ancestor.body).node === candidate.node
     ? returnedPromiseOwnership(
         candidate.ownerCallableId,
         range(ancestor.body),
@@ -276,7 +282,7 @@ const assignedPromiseBinding = (
     ? ancestor.init
     : ancestor.right;
   if (source == null) return undefined;
-  if (unwrapExpression(source) !== candidate) return undefined;
+  if (unwrapJavaScriptExpression(source).node !== candidate) return undefined;
   return scalarAssignedResultBinding(
     assignedSemanticResultBindings(source, [ancestor], state),
   );
@@ -302,7 +308,8 @@ const outerConsumesCandidate = (
   ) {
     const member = dataEffectMemberCallee(outer.node);
     return (
-      member !== null && unwrapExpression(member.object) === candidate.node
+      member !== null &&
+      unwrapJavaScriptExpression(member.object).node === candidate.node
     );
   }
   if (
@@ -316,7 +323,7 @@ const outerConsumesCandidate = (
         (element) =>
           element !== null &&
           !t.isSpreadElement(element) &&
-          unwrapExpression(element) === candidate.node,
+          unwrapJavaScriptExpression(element).node === candidate.node,
       )
     );
   }
@@ -441,7 +448,7 @@ const resolvePromiseExpression = (
   context: PromiseExpressionResolutionContext,
 ): PromiseResolution => {
   const { current, candidateByNode, state, seenBindings } = context;
-  const node = unwrapExpression(rawNode);
+  const node = unwrapJavaScriptExpression(rawNode).node;
   const direct = candidateByNode.get(node);
   if (direct !== undefined && direct.promiseId !== current.promiseId)
     return { promiseIds: [direct.promiseId], status: "complete" };
@@ -476,18 +483,6 @@ const promiseResolutionContext = (
   seenBindings: new Set(),
 });
 
-const unwrapExpression = (node: t.Node): t.Node => {
-  if (
-    t.isParenthesizedExpression(node) ||
-    t.isTSAsExpression(node) ||
-    t.isTSSatisfiesExpression(node) ||
-    t.isTSNonNullExpression(node) ||
-    t.isTypeCastExpression(node)
-  )
-    return unwrapExpression(node.expression);
-  return node;
-};
-
 const combinePromiseResolutions = (
   resolutions: readonly PromiseResolution[],
 ): PromiseResolution => ({
diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts
index e0bf54046..b5159afc8 100644
--- a/src/domain/javascript/javascriptSemanticRequireOrigin.ts
+++ b/src/domain/javascript/javascriptSemanticRequireOrigin.ts
@@ -6,7 +6,10 @@ import {
   semanticResolutionBlocked,
   type JavaScriptSemanticAnalysisState,
 } from "./javascriptSemanticState.js";
-import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
+import {
+  semanticStaticPropertyKey,
+  unwrapJavaScriptExpression,
+} from "./javascriptAstValues.js";
 import { stringValue } from "./javascriptStaticAnalysisHelpers.js";
 
 /** Recover an unshadowed literal require origin and its exact member path. */
@@ -15,23 +18,34 @@ export const semanticRequireOrigin = (
   state: JavaScriptSemanticAnalysisState,
 ): JavaScriptModuleOrigin | undefined => {
   const members: string[] = [];
-  while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
-    const member = semanticStaticPropertyKey(node.property, node.computed);
-    if (member === null || !t.isNode(node.object)) return undefined;
+  let current = node;
+  while (current !== null && current !== undefined) {
+    current = unwrapJavaScriptExpression(current).node;
+    if (
+      !t.isMemberExpression(current) &&
+      !t.isOptionalMemberExpression(current)
+    )
+      break;
+    const member = semanticStaticPropertyKey(
+      current.property,
+      current.computed,
+    );
+    if (member === null || !t.isNode(current.object)) return undefined;
     members.push(member);
-    node = node.object;
+    current = current.object;
   }
   if (
-    !t.isCallExpression(node) ||
-    !t.isIdentifier(node.callee, { name: "require" })
+    !t.isCallExpression(current) ||
+    !t.isIdentifier(current.callee, { name: "require" })
   )
     return undefined;
   if (
-    resolveSemanticBindingState(state, node.callee, "require") !== undefined ||
-    semanticResolutionBlocked(state, node.callee, "require")
+    resolveSemanticBindingState(state, current.callee, "require") !==
+      undefined ||
+    semanticResolutionBlocked(state, current.callee, "require")
   )
     return undefined;
-  const specifier = stringValue(node.arguments[0]);
+  const specifier = stringValue(current.arguments[0]);
   return specifier === undefined
     ? undefined
     : { specifier, importedPath: members.reverse() };
diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts
index 13e68279a..95228ea3e 100644
--- a/src/domain/javascript/javascriptSemanticReturns.ts
+++ b/src/domain/javascript/javascriptSemanticReturns.ts
@@ -17,6 +17,7 @@ import type {
 } from "./javascriptExportShapeComparisonSchemas.js";
 import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js";
+import { unwrapJavaScriptExpression } from "./javascriptAstValues.js";
 import {
   resolveSemanticBindingState,
   type JavaScriptSemanticAnalysisState,
@@ -177,6 +178,9 @@ const callableIdsForNode = (
   admitted: ReadonlySet,
   seen: ReadonlySet,
 ): string[] => {
+  const unwrapped = unwrapJavaScriptExpression(node).node;
+  if (unwrapped !== node)
+    return callableIdsForNode(unwrapped, state, admitted, seen);
   const direct = semanticCallableIdForNode(node);
   if (direct !== null && admitted.has(direct)) return [direct];
   if (t.isIdentifier(node)) {
@@ -185,13 +189,6 @@ const callableIdsForNode = (
       ? []
       : callableIdsForBinding(binding, state, admitted, seen);
   }
-  if (
-    t.isTSAsExpression(node) ||
-    t.isTSTypeAssertion(node) ||
-    t.isTSNonNullExpression(node) ||
-    t.isTSSatisfiesExpression(node)
-  )
-    return callableIdsForNode(node.expression, state, admitted, seen);
   return [];
 };
 
diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts
index d0eb007b5..39380a9c0 100644
--- a/src/domain/javascript/javascriptSemanticValues.ts
+++ b/src/domain/javascript/javascriptSemanticValues.ts
@@ -20,6 +20,7 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 import {
   readExactJavaScriptLiteral,
   semanticStaticPropertyKey,
+  unwrapJavaScriptExpression,
 } from "./javascriptAstValues.js";
 import {
   semanticAmbiguousProvenance,
@@ -170,6 +171,18 @@ const evaluateExpression = (
 ): JavaScriptSemanticValue => {
   if (context.expressionDepth > SEMANTIC_EXPRESSION_DEPTH_LIMIT)
     return semanticResourceLimitUnknown("expression-depth");
+  const unwrapped = unwrapJavaScriptExpression(node);
+  if (unwrapped.depth > 0) {
+    if (
+      context.expressionDepth + unwrapped.depth >
+      SEMANTIC_EXPRESSION_DEPTH_LIMIT
+    )
+      return semanticResourceLimitUnknown("expression-depth");
+    return evaluateExpression(unwrapped.node, {
+      ...context,
+      expressionDepth: context.expressionDepth + unwrapped.depth,
+    });
+  }
   const literal = readExactJavaScriptLiteral(node);
   if (literal.found)
     return typeof literal.value === "number"
@@ -199,14 +212,6 @@ const evaluateExpression = (
   if (t.isBinaryExpression(node, { operator: "+" }))
     return evaluateAddition(node, context);
   if (t.isUnaryExpression(node)) return evaluateUnary(node, context);
-  if (
-    (t.isTSAsExpression(node) ||
-      t.isTSTypeAssertion(node) ||
-      t.isTSNonNullExpression(node) ||
-      t.isTSSatisfiesExpression(node)) &&
-    t.isExpression(node.expression)
-  )
-    return evaluateExpression(node.expression, nestedContext(context));
   return { status: "unknown", reason: `Unsupported ${node.type} value.` };
 };
 
@@ -531,6 +536,21 @@ const provenanceForExpression = (
       "unknown",
       semanticResourceLimitReason("expression-depth"),
     );
+  const unwrapped = unwrapJavaScriptExpression(node);
+  if (unwrapped.depth > 0) {
+    if (
+      context.expressionDepth + unwrapped.depth >
+      SEMANTIC_EXPRESSION_DEPTH_LIMIT
+    )
+      return semanticUnresolvedProvenance(
+        "unknown",
+        semanticResourceLimitReason("expression-depth"),
+      );
+    return provenanceForExpression(unwrapped.node, {
+      ...context,
+      expressionDepth: context.expressionDepth + unwrapped.depth,
+    });
+  }
   const required = semanticRequireOrigin(node, context.state);
   if (required !== undefined) return semanticOriginsProvenance([required]);
   if (t.isIdentifier(node)) {
diff --git a/src/domain/javascript/javascriptSourceParser.ts b/src/domain/javascript/javascriptSourceParser.ts
index 86d030bc3..e413e0cb4 100644
--- a/src/domain/javascript/javascriptSourceParser.ts
+++ b/src/domain/javascript/javascriptSourceParser.ts
@@ -8,9 +8,14 @@ export const parseJavaScriptSource = (
   source: string,
   sourcePath?: string,
 ): ParsedJavaScriptSource | null => {
+  const path = sourcePath ?? "";
+  const isMts = /\.mts$/iu.test(path);
   const typescript: ParserPlugin = [
     "typescript",
-    { dts: /\.d\.(?:ts|mts|cts)$/iu.test(sourcePath ?? "") },
+    {
+      dts: /\.d\.(?:ts|mts|cts)$/iu.test(path),
+      ...(isMts ? { disallowAmbiguousJSXLike: true } : {}),
+    },
   ];
   try {
     return parse(source, {
@@ -21,9 +26,10 @@ export const parseJavaScriptSource = (
       // forms, including parameter decorators. Without it a decorated
       // TypeScript source fails to parse at all rather than reporting
       // recovered syntax, which loses every fact derived from that source.
+      // TypeScript's .mts mode disables JSX and rejects ambiguous angle syntax.
       // Plain .ts and .cts artifacts admit angle-bracket type assertions instead of JSX.
       // Unknown paths retain the existing JSX-capable parser contract.
-      plugins: /\.(?:ts|cts)$/iu.test(sourcePath ?? "")
+      plugins: /\.(?:ts|cts|mts)$/iu.test(path)
         ? ["decorators-legacy", typescript]
         : ["decorators-legacy", "jsx", typescript],
     });
diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts
index ed1cd8e21..25cd0fcbc 100644
--- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts
+++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts
@@ -14,6 +14,7 @@ import type {
 import {
   readExactJavaScriptLiteral,
   semanticStaticPropertyName,
+  unwrapJavaScriptExpression,
 } from "./javascriptAstValues.js";
 import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 
@@ -100,8 +101,8 @@ const findChunkRuntime = (node: t.Node): string | undefined => {
       pending.push(current.right, current.left);
       continue;
     }
-    if (t.isParenthesizedExpression(current) || t.isTSAsExpression(current))
-      pending.push(current.expression);
+    const unwrapped = unwrapJavaScriptExpression(current).node;
+    if (unwrapped !== current) pending.push(unwrapped);
   }
   return undefined;
 };
diff --git a/src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts b/src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts
index 075597a70..4c585786c 100644
--- a/src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts
+++ b/src/domain/javascript/javascriptStaticAnalysisModuleIndex.test.ts
@@ -67,3 +67,15 @@ it("keeps module references attributed across many real factory ranges", () => {
     )?.module_key,
   ).toBe("module-0");
 });
+
+it("retains the chunk runtime through a TypeScript-only expression wrapper", () => {
+  const analysis = analyzeJavaScriptStaticSource(
+    '(globalThis.webpackChunkApp satisfies unknown).push([[1], { "entry": function () {} }]);',
+  );
+  expect(analysis.bundler_registrations).toEqual([
+    expect.objectContaining({
+      runtime: "webpackChunkApp",
+      modules: [expect.objectContaining({ module_key: "entry" })],
+    }),
+  ]);
+});

From 3e19875c7fa9c61cff655bbe6046ddc4ab558533 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:39:37 +0800
Subject: [PATCH 039/189] fix(javascript): retain unresolved value frontiers in
 provenance queries

---
 .../JavaScriptApplicationSignedZero.test.ts   | 78 +++++++++++++++----
 .../JavaScriptSemanticGraphBuilder.test.ts    |  3 +-
 .../JavaScriptSemanticGraphValueProjection.ts | 16 ++--
 .../javascriptSemanticGraphSchemas.ts         |  1 +
 4 files changed, 75 insertions(+), 23 deletions(-)

diff --git a/src/application/javascript/JavaScriptApplicationSignedZero.test.ts b/src/application/javascript/JavaScriptApplicationSignedZero.test.ts
index b1f4df0ba..a36c1fdab 100644
--- a/src/application/javascript/JavaScriptApplicationSignedZero.test.ts
+++ b/src/application/javascript/JavaScriptApplicationSignedZero.test.ts
@@ -5,22 +5,66 @@ import { expect, it } from "vitest";
 
 import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
 import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { javaScriptSemanticQueryResultSchema } from "../../domain/javascript/javascriptSemanticQuerySchemas.js";
+import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
 import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
 
-it("does not expose a resolved positive-zero literal for a negative-zero export", async () => {
-  const root = await createTestTempDirectory("rea-signed-zero-");
-  await writeFile(join(root, "app.js"), "export const value = -0;\n");
-  const result = await analyzeJavaScriptApplication({
-    input_path: root,
-    format: "directory",
-  });
-  if (!result.ok) throw result.error;
-  const analysis = javascriptApplicationAnalysisResultSchema.parse(
-    result.value.normalized_result,
-  );
-  expect(
-    analysis.semantic_graph.nodes.filter(
-      ({ kind, properties }) => kind === "literal" && properties.value === 0,
-    ),
-  ).toEqual([]);
-});
+it.each([
+  {
+    source: "export const value = -0;\n",
+    target: { kind: "binding", label: "value" },
+  },
+  {
+    source: "export const root = { value: -0 };\n",
+    target: { kind: "property-slot", propertyPointer: "/value" },
+  },
+])(
+  "keeps negative-zero value unknown in an exported query (%#)",
+  async ({ source, target }) => {
+    const root = await createTestTempDirectory("rea-signed-zero-");
+    await writeFile(join(root, "app.js"), source);
+    const result = await analyzeJavaScriptApplication({
+      input_path: root,
+      format: "directory",
+    });
+    if (!result.ok) throw result.error;
+    const analysis = javascriptApplicationAnalysisResultSchema.parse(
+      result.value.normalized_result,
+    );
+    const node =
+      target.kind === "binding"
+        ? analysis.semantic_graph.nodes.find(
+            ({ kind, label }) => kind === "binding" && label === target.label,
+          )
+        : analysis.semantic_graph.nodes.find(
+            ({ kind, properties }) =>
+              kind === "property-slot" &&
+              properties.property_pointer === target.propertyPointer,
+          );
+    if (node === undefined)
+      throw new Error("Expected the selected semantic node");
+    const query = queryJavaScriptSemanticGraph(analysis.semantic_graph, {
+      seed: { kind: "semantic-node", node_id: node.node_id },
+      direction: "backward-provenance",
+      allowed_relations: ["defines"],
+    });
+    const transportedQuery = javaScriptSemanticQueryResultSchema.parse(
+      JSON.parse(JSON.stringify(query)),
+    );
+    expect(transportedQuery.nodes.some(({ kind }) => kind === "literal")).toBe(
+      false,
+    );
+    expect(transportedQuery.coverage.status).toBe("partial");
+    expect(transportedQuery.unknowns).toEqual(
+      expect.arrayContaining([
+        expect.objectContaining({
+          reason: "unknown-value",
+          node_id: node.node_id,
+          detail: expect.stringContaining(
+            "Negative zero cannot be preserved by JSON primitive evidence.",
+          ),
+        }),
+      ]),
+    );
+  },
+);
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
index af74de616..6dd3f8576 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
@@ -145,7 +145,8 @@ it("retains resource-limit reasons at nested object property slots", () => {
   ]);
   expect(graph.unknowns).toContainEqual(
     expect.objectContaining({
-      family: "object-flow",
+      family: "data-flow",
+      relation_kinds: ["defines"],
       reason: "resource-limit",
       detail: expect.stringMatching(
         /Unknown value at property:\/nested\/value/u,
diff --git a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
index cb2596b28..bcc9db294 100644
--- a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
@@ -111,17 +111,23 @@ const projectValue = (input: ValueProjectionInput): void => {
           ),
         }),
       );
-  } else if (value.status === "unknown" && value.resourceLimit !== undefined) {
+  } else if (
+    value.status === "unknown" ||
+    value.status === "ambiguous" ||
+    value.status === "cycle"
+  ) {
     const location = binding.definitions[0]?.location ?? null;
     const evidence = observedSemanticEvidence(context.file, location);
-    const isPropertyValue = role.startsWith("property:");
     addSemanticGraphUnknown(
       context.state,
       createJavaScriptSemanticGraphUnknown({
         node_id: target.node_id,
-        family: isPropertyValue ? "object-flow" : "data-flow",
-        relation_kinds: [isPropertyValue ? "writes-property" : "defines"],
-        reason: "resource-limit",
+        family: "data-flow",
+        relation_kinds: ["defines"],
+        reason:
+          value.resourceLimit === undefined
+            ? "unknown-value"
+            : "resource-limit",
         detail: `${value.reason} Unknown value at ${role}.`,
         candidate_node_ids: [target.node_id],
         evidence: {
diff --git a/src/domain/javascript/javascriptSemanticGraphSchemas.ts b/src/domain/javascript/javascriptSemanticGraphSchemas.ts
index c5374ebe4..64e704198 100644
--- a/src/domain/javascript/javascriptSemanticGraphSchemas.ts
+++ b/src/domain/javascript/javascriptSemanticGraphSchemas.ts
@@ -251,6 +251,7 @@ export const JAVASCRIPT_SEMANTIC_UNKNOWN_REASONS = [
   "incomplete-module",
   "missing-source",
   "resource-limit",
+  "unknown-value",
   "unsupported-syntax",
 ] as const;
 

From 41a228c1b01a89127858b1706879ede08a81deaf Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:39:45 +0800
Subject: [PATCH 040/189] fix(electron): preserve unrepresentable numeric
 option evidence

---
 .../electronStaticAnalysisValues.ts           |  8 +++++--
 .../electronOptionKeys.test.ts                | 23 +++++++++++++++++++
 2 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/src/domain/javascript/electronStaticAnalysisValues.ts b/src/domain/javascript/electronStaticAnalysisValues.ts
index 796c5a397..2a800e6bb 100644
--- a/src/domain/javascript/electronStaticAnalysisValues.ts
+++ b/src/domain/javascript/electronStaticAnalysisValues.ts
@@ -151,7 +151,11 @@ const literalValue = (
   if (
     t.isUnaryExpression(node, { operator: "-" }) &&
     t.isNumericLiteral(node.argument)
-  )
-    return { found: true, value: -node.argument.value };
+  ) {
+    const value = -node.argument.value;
+    return Number.isFinite(value) && !Object.is(value, -0)
+      ? { found: true, value }
+      : { found: false };
+  }
   return { found: false };
 };
diff --git a/tests/composition/javascript-applications/electronOptionKeys.test.ts b/tests/composition/javascript-applications/electronOptionKeys.test.ts
index 7ab18b952..b05162fa9 100644
--- a/tests/composition/javascript-applications/electronOptionKeys.test.ts
+++ b/tests/composition/javascript-applications/electronOptionKeys.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest";
 
 import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
 
 const PRELOAD = '{ preload: "./preload.js", sandbox: true }';
 const EXPLICIT = `webPreferences: ${PRELOAD}`;
@@ -124,6 +125,28 @@ describe("Electron option keys in reconstructed application graphs", () => {
       evidence: { coverage: { status: "partial" } },
     });
   });
+
+  it.each([
+    ["-0", { status: "dynamic", value: null, expression: "-0" }],
+    ["-0.0", { status: "dynamic", value: null, expression: "-0.0" }],
+    ["-1e999", { status: "dynamic", value: null, expression: "-1e999" }],
+    ["-1", { status: "literal", value: -1, expression: null }],
+  ] as const)(
+    "preserves the JSON representation of BrowserWindow preference %s",
+    async (expression, value) => {
+      const result = await reconstructSource(
+        `new BrowserWindow({ webPreferences: { zoomFactor: ${expression} } });`,
+      );
+      const graph: unknown = JSON.parse(JSON.stringify(result.graph));
+      const transported = parseJavaScriptApplicationGraph(graph);
+      const window = transported.nodes.find(
+        ({ kind }) => kind === "browser-window",
+      );
+      expect(window?.observations[0]?.properties.web_preferences).toEqual([
+        { name: "zoomFactor", value },
+      ]);
+    },
+  );
 });
 
 type Reconstruction = Awaited>;

From 96b2b245fdefc9c78f5dcf6ce054232b51f7c117 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:39:52 +0800
Subject: [PATCH 041/189] test(javascript): verify distinct module origins
 through reconstruction

---
 ...criptSemanticAnalysis.origin_paths.test.ts | 16 ---------
 .../javascriptModuleRelationships.test.ts     | 33 +++++++++++++++++++
 2 files changed, 33 insertions(+), 16 deletions(-)
 delete mode 100644 src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts

diff --git a/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts
deleted file mode 100644
index c3e12d327..000000000
--- a/src/domain/javascript/javascriptSemanticAnalysis.origin_paths.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { expect, it } from "vitest";
-
-import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
-import { topLevelBinding } from "./javascriptSemanticAnalysis.fixture.js";
-
-it("retains distinct module origins when a property contains the old separator", () => {
-  const result = analyzeJavaScriptSemantics(
-    'import * as ns from "./fixture.js"; const selected = choice ? ns["a\\0b"] : ns.a.b;',
-  );
-  const provenance = topLevelBinding(result, "selected").provenance;
-  expect(provenance.status).toBe("ambiguous");
-  expect(provenance.origins.map(({ importedPath }) => importedPath)).toEqual(
-    expect.arrayContaining([["a\0b"], ["a", "b"]]),
-  );
-  expect(provenance.origins).toHaveLength(2);
-});
diff --git a/tests/composition/javascript-applications/javascriptModuleRelationships.test.ts b/tests/composition/javascript-applications/javascriptModuleRelationships.test.ts
index 2db52caa5..ca6981ebb 100644
--- a/tests/composition/javascript-applications/javascriptModuleRelationships.test.ts
+++ b/tests/composition/javascript-applications/javascriptModuleRelationships.test.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
 import { describe, expect, it } from "vitest";
 
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
 
 import {
   findExportNode,
@@ -149,6 +150,38 @@ describe("CommonJS and ESM module relationships", () => {
   });
 });
 
+it("does not assign one module origin to an export with colliding path encodings", async () => {
+  const root = await createTestTempDirectory("rea-ambiguous-module-origin-");
+  await writeFixtureFiles(root, {
+    "index.js": String.raw`
+        import * as ns from "./fixture.js";
+        const selected = choice ? ns["a\0b"] : ns.a.b;
+        export { selected };
+      `,
+    "fixture.js": "export const fixture = true;\n",
+  });
+  const { graph } = await reconstructJavaScriptFixture(root);
+  const applicationGraph = parseJavaScriptApplicationGraph(
+    JSON.parse(JSON.stringify(graph)),
+  );
+  const selectedExport = findExportNode(
+    applicationGraph,
+    "index.js",
+    "selected",
+  );
+  if (selectedExport === undefined)
+    throw new Error("Expected the selected export node");
+
+  expect(
+    applicationGraph.edges.filter(
+      ({ relation, source_node_id, properties }) =>
+        relation === "imports" &&
+        source_node_id === selectedExport.node_id &&
+        properties.local_name === "selected",
+    ),
+  ).toEqual([]);
+});
+
 describe("complete static application projections", () => {
   it("retains exports and JSON keys beyond the former projection prefix", async () => {
     const root = await moduleFixture();

From 5a61562dc200120c7b8020854085c17b8203e95d Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:40:18 +0800
Subject: [PATCH 042/189] test(browser): report redirect status cases
 independently

---
 .../browser/webSourceMapHttpStatus.test.ts    | 130 +++++++++---------
 1 file changed, 64 insertions(+), 66 deletions(-)

diff --git a/tests/boundary/browser/webSourceMapHttpStatus.test.ts b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
index 2b229e76d..69763ddf9 100644
--- a/tests/boundary/browser/webSourceMapHttpStatus.test.ts
+++ b/tests/boundary/browser/webSourceMapHttpStatus.test.ts
@@ -6,43 +6,50 @@ import { expect, it } from "vitest";
 import { fetchWebSourceMaps } from "../../../src/browser/WebSourceMapFetcher.js";
 import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
 
-it("follows only HTTP redirect statuses when a source-map response carries Location", async () => {
-  const calls: string[] = [];
-  const server = createServer((request, response) => {
-    const path = request.url ?? "";
-    calls.push(path);
-    if (path === "/delivered.map") {
-      response.writeHead(200, { "content-type": "application/json" }).end(
-        JSON.stringify({
-          version: 3,
-          names: [],
-          sources: ["original.js"],
-          mappings: "AAAA",
-        }),
-      );
-      return;
-    }
-    response
-      .writeHead(Number(path.slice(1)), { location: "/delivered.map" })
-      .end();
-  });
-  try {
-    const listening = once(server, "listening");
-    server.listen(0, "127.0.0.1");
-    await listening;
-    const address = server.address();
-    if (address === null || typeof address === "string")
-      throw new TypeError("Expected TCP listener");
-    const origin = `http://127.0.0.1:${String(address.port)}`;
-    const input = analyzeWebBundleInputSchema.parse({
-      cdp_endpoint: "http://127.0.0.1:9222",
-      target_id: "selected-page",
-      allowed_origins: [origin],
-      fetch_source_maps: true,
+it.each([
+  { status: 300, followsRedirect: false },
+  { status: 304, followsRedirect: false },
+  { status: 305, followsRedirect: false },
+  { status: 306, followsRedirect: false },
+  { status: 301, followsRedirect: true },
+  { status: 302, followsRedirect: true },
+  { status: 303, followsRedirect: true },
+  { status: 307, followsRedirect: true },
+  { status: 308, followsRedirect: true },
+])(
+  "follows HTTP $status with Location only when it is a redirect status",
+  async ({ status, followsRedirect }) => {
+    const calls: string[] = [];
+    const server = createServer((request, response) => {
+      const path = request.url ?? "";
+      calls.push(path);
+      if (path === "/delivered.map") {
+        response.writeHead(200, { "content-type": "application/json" }).end(
+          JSON.stringify({
+            version: 3,
+            names: [],
+            sources: ["original.js"],
+            mappings: "AAAA",
+          }),
+        );
+        return;
+      }
+      response.writeHead(status, { location: "/delivered.map" }).end();
     });
-    const failures: unknown[] = [];
-    for (const status of [300, 304, 305, 306, 301, 302, 303, 307, 308]) {
-      calls.length = 0;
+    try {
+      const listening = once(server, "listening");
+      server.listen(0, "127.0.0.1");
+      await listening;
+      const address = server.address();
+      if (address === null || typeof address === "string")
+        throw new TypeError("Expected TCP listener");
+      const origin = `http://127.0.0.1:${String(address.port)}`;
+      const input = analyzeWebBundleInputSchema.parse({
+        cdp_endpoint: "http://127.0.0.1:9222",
+        target_id: "selected-page",
+        allowed_origins: [origin],
+        fetch_source_maps: true,
+      });
       const url = `${origin}/${String(status)}`;
       const result = await fetchWebSourceMaps(
         [
@@ -54,36 +61,27 @@ it("follows only HTTP redirect statuses when a source-map response carries Locat
         ],
         input,
       );
-      const redirect = [301, 302, 303, 307, 308].includes(status);
-      try {
-        expect([...calls]).toEqual(
-          redirect
-            ? [`/${String(status)}`, "/delivered.map"]
-            : [`/${String(status)}`],
+
+      expect(calls).toEqual(
+        followsRedirect
+          ? [`/${String(status)}`, "/delivered.map"]
+          : [`/${String(status)}`],
+      );
+      expect(result.items[0]?.status).toBe(
+        followsRedirect ? "included" : "fetch_failed",
+      );
+      if (!followsRedirect)
+        expect(result.items[0]?.limitation).toBe(
+          `Source-map server returned HTTP ${String(status)}.`,
         );
-        expect(result.items[0]?.status).toBe(
-          redirect ? "included" : "fetch_failed",
+    } finally {
+      server.closeAllConnections();
+      if (server.listening)
+        await new Promise((resolve, reject) =>
+          server.close((error) =>
+            error === undefined ? resolve() : reject(error),
+          ),
         );
-        if (!redirect)
-          expect(result.items[0]?.limitation).toBe(
-            `Source-map server returned HTTP ${String(status)}.`,
-          );
-      } catch (cause) {
-        failures.push(cause);
-      }
     }
-    if (failures.length > 0)
-      throw new AggregateError(
-        failures,
-        "Nonredirect source-map responses were followed",
-      );
-  } finally {
-    server.closeAllConnections();
-    if (server.listening)
-      await new Promise((resolve, reject) =>
-        server.close((error) =>
-          error === undefined ? resolve() : reject(error),
-        ),
-      );
-  }
-});
+  },
+);

From 377df715ea5b2523cd6c1084fdc286eb8a056182 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:42:19 +0800
Subject: [PATCH 043/189] refactor(reference): simplify malformed UTF-8
 handling

---
 src/domain/referenceSourceImportParsing.ts | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/src/domain/referenceSourceImportParsing.ts b/src/domain/referenceSourceImportParsing.ts
index 7f9ad996a..1abfc6a51 100644
--- a/src/domain/referenceSourceImportParsing.ts
+++ b/src/domain/referenceSourceImportParsing.ts
@@ -334,10 +334,7 @@ export const parseReferenceSourceImports = (
   let source: string;
   try {
     source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
-  } catch (cause: unknown) {
-    // The import still records the original bytes; lossy text cannot supply
-    // observed module names or relationships.
-    void cause;
+  } catch {
     return {
       relationships: [],
       parse_failures: [

From 74be52611e66f680ef1919d521fc3c304bc2326e Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:42:33 +0800
Subject: [PATCH 044/189] test(process): publish capture readiness atomically

---
 tests/fixtures/processCaptureCancellation.mjs | 33 ++++++++++---------
 1 file changed, 17 insertions(+), 16 deletions(-)

diff --git a/tests/fixtures/processCaptureCancellation.mjs b/tests/fixtures/processCaptureCancellation.mjs
index 6bfad03b6..501588b20 100644
--- a/tests/fixtures/processCaptureCancellation.mjs
+++ b/tests/fixtures/processCaptureCancellation.mjs
@@ -1,23 +1,27 @@
 import { spawn } from "node:child_process";
-import { writeFile } from "node:fs/promises";
+import { rename, writeFile } from "node:fs/promises";
 import { join } from "node:path";
 
 const [mode, root] = process.argv.slice(2);
 
+const publishReadyMarker = async (marker) => {
+  const destination = join(root, "ready.json");
+  const temporary = join(root, "ready.json.tmp");
+  await writeFile(temporary, JSON.stringify(marker));
+  await rename(temporary, destination);
+};
+
 if (mode === "settlement") {
   const child = spawn(process.execPath, [process.argv[1], "workload", root], {
     stdio: ["ignore", "ignore", "ignore", "ipc"],
   });
   child.on("message", async (message) => {
     if (message !== "ready" || child.pid === undefined) return;
-    await writeFile(
-      join(root, "ready.json"),
-      JSON.stringify({
-        rootPid: process.pid,
-        childPid: child.pid,
-        runId: process.env.REA_PROCESS_RUN_ID,
-      }),
-    );
+    await publishReadyMarker({
+      rootPid: process.pid,
+      childPid: child.pid,
+      runId: process.env.REA_PROCESS_RUN_ID,
+    });
     child.disconnect();
     child.unref();
     process.stdout.write("root exiting; owned workload remains\n");
@@ -33,13 +37,10 @@ if (mode === "settlement") {
   setTimeout(() => process.exit(0), 12_000);
   if (mode === "workload") process.send?.("ready");
   else {
-    await writeFile(
-      join(root, "ready.json"),
-      JSON.stringify({
-        rootPid: process.pid,
-        runId: process.env.REA_PROCESS_RUN_ID,
-      }),
-    );
+    await publishReadyMarker({
+      rootPid: process.pid,
+      runId: process.env.REA_PROCESS_RUN_ID,
+    });
     process.stdout.write("owned workload ready\n");
   }
 }

From 4940a867e2e56cbb974bfa321008a8f35db47d52 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:42:58 +0800
Subject: [PATCH 045/189] test(process): use owned CLI and workspace fixtures

---
 tests/boundary/process/processCli.test.ts | 63 +++++++++--------------
 1 file changed, 25 insertions(+), 38 deletions(-)

diff --git a/tests/boundary/process/processCli.test.ts b/tests/boundary/process/processCli.test.ts
index 418648105..3da9205f6 100644
--- a/tests/boundary/process/processCli.test.ts
+++ b/tests/boundary/process/processCli.test.ts
@@ -1,13 +1,14 @@
-import { readFile, rm, writeFile } from "node:fs/promises";
+import { readFile, writeFile } from "node:fs/promises";
 import { join } from "node:path";
 import { fileURLToPath } from "node:url";
 
 import { execFile } from "node:child_process";
 import { promisify } from "node:util";
 
-import { afterEach, describe, expect, it } from "vitest";
+import { describe, expect, it } from "vitest";
 
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
 
 import {
   captureProcessScenarioFile,
@@ -19,27 +20,14 @@ import { ProcessCaptureError } from "../../../src/process/capture/ProcessCapture
 import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
 import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
 
-const roots: string[] = [];
 const execFileAsync = promisify(execFile);
 const CLI_INTEGRATION_TIMEOUT_MS = 60_000;
 
-afterEach(async () => {
-  await Promise.all(
-    roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
-  );
-});
-
-const fixture = async (): Promise => {
-  const root = await createTestTempDirectory("rea-process-cli-");
-  roots.push(root);
-  return root;
-};
-
 describe("documented process CLI workflow", () => {
-  it(
+  cliTest(
     "feeds the documented JSON capture into the comparison CLI",
-    async () => {
-      const root = await fixture();
+    async ({ cli }) => {
+      const root = await createTestTempDirectory("rea-process-cli-");
       const guide = await readFile(
         new URL("../../../docs/process-capture.md", import.meta.url),
         "utf8",
@@ -62,24 +50,23 @@ describe("documented process CLI workflow", () => {
           arguments: ["-e", "process.stdout.write('documented-capture')"],
         }),
       );
-      const cli = fileURLToPath(
-        new URL("../../../scripts/rea.mjs", import.meta.url),
-      );
-      const capture = await execFileAsync(
-        process.execPath,
-        [cli, "capture-process", ...args],
-        { cwd: root },
-      );
-      expect(JSON.parse(capture.stdout)).toMatchObject({
+      const capture = await cli.run({
+        arguments: ["capture-process", ...args],
+        cwd: root,
+      });
+      expect(capture.exitCode, capture.stdout || capture.stderr).toBe(0);
+      expect(capture.json).toMatchObject({
         operation: "capture_process_scenario",
       });
       await writeFile(join(root, output), capture.stdout);
-      const comparison = await execFileAsync(
-        process.execPath,
-        [cli, "compare-process-captures", output, output, "--json"],
-        { cwd: root },
+      const comparison = await cli.run({
+        arguments: ["compare-process-captures", output, output, "--json"],
+        cwd: root,
+      });
+      expect(comparison.exitCode, comparison.stdout || comparison.stderr).toBe(
+        0,
       );
-      expect(JSON.parse(comparison.stdout)).toMatchObject({
+      expect(comparison.json).toMatchObject({
         operation: "compare_process_captures",
       });
     },
@@ -106,7 +93,7 @@ describe("process CLI errors", () => {
   );
 
   it("rejects NUL arguments before process launch", async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const scenario = join(root, "nul-argument.json");
     await writeFile(
       scenario,
@@ -135,7 +122,7 @@ describe("process CLI errors", () => {
 
 describe("process CLI environment key diagnostics", () => {
   it("reports the reserved process environment key constraint", async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const scenario = join(root, "reserved-environment.json");
     await writeFile(
       scenario,
@@ -190,7 +177,7 @@ describe("process CLI evidence validation", () => {
   });
 
   it("captures the minimal executable-and-arguments scenario", async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const scenario = join(root, "scenario.json");
     await writeFile(
       scenario,
@@ -208,7 +195,7 @@ describe("process CLI evidence validation", () => {
   });
 
   it("rejects unrelated capture evidence", async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const invalidCapture = join(root, "invalid-capture.json");
     const unrelated = join(root, "unrelated.json");
     await writeFile(
@@ -249,7 +236,7 @@ describe("process CLI evidence validation", () => {
   });
 
   it("classifies malformed capture evidence as invalid input", async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const malformed = join(root, "malformed-evidence.json");
     await writeFile(malformed, "{}");
 
@@ -275,7 +262,7 @@ describe("process CLI evidence validation", () => {
 it(
   "reports the JSON depth constraint through the compiled comparison CLI",
   async () => {
-    const root = await fixture();
+    const root = await createTestTempDirectory("rea-process-cli-");
     const left = join(root, "left.json");
     const right = join(root, "right.json");
     const input = INVESTIGATION_EXAMPLES.compare_process_captures.input;

From cfce91d418fbcde4a9ef283a61549279751854e7 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:44:52 +0800
Subject: [PATCH 046/189] fix(browser): serialize attached scenarios through
 cleanup settlement

---
 scripts/fixtures/browser-verifier-site.mjs    |  14 +-
 .../lib/browser-scenario-environment-e2e.mjs  | 192 +++++++++++--
 .../PlaywrightBrowserScenarioProvider.test.ts |   4 +
 src/browser/PlaywrightScenarioBrowser.test.ts | 262 +++++++++++++++--
 src/browser/PlaywrightScenarioBrowser.ts      | 272 +++++++++++++++---
 src/browser/PlaywrightScenarioSession.ts      |   4 +-
 6 files changed, 668 insertions(+), 80 deletions(-)

diff --git a/scripts/fixtures/browser-verifier-site.mjs b/scripts/fixtures/browser-verifier-site.mjs
index 208a314a2..059a63599 100644
--- a/scripts/fixtures/browser-verifier-site.mjs
+++ b/scripts/fixtures/browser-verifier-site.mjs
@@ -11,9 +11,14 @@ export async function startBrowserVerifierSite() {
       response.destroy();
       return;
     }
-    if (request.url === "/scenario-environment") {
+    const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
+    if (requestUrl.pathname === "/scenario-environment") {
+      const requestedRun = requestUrl.searchParams.get("run");
+      const run = ["A", "B", "C"].includes(requestedRun)
+        ? requestedRun
+        : "default";
       response.setHeader("content-type", "text/html");
-      response.end(`

+      response.end(`

         `);
       return;
diff --git a/scripts/lib/browser-scenario-environment-e2e.mjs b/scripts/lib/browser-scenario-environment-e2e.mjs
index bc460192d..1804402f3 100644
--- a/scripts/lib/browser-scenario-environment-e2e.mjs
+++ b/scripts/lib/browser-scenario-environment-e2e.mjs
@@ -17,43 +17,68 @@ const expected = {
   width: 900,
   height: 600,
 };
+const alternate = {
+  timezone: "UTC",
+  locale: "en-US",
+  dpr: 1,
+  width: 700,
+  height: 500,
+};
 const expression = `JSON.stringify({
   timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
   locale: Intl.DateTimeFormat().resolvedOptions().locale,
   dpr: devicePixelRatio, width: innerWidth, height: innerHeight
 })`;
 
-const environmentScenario = (endpoint, targetId, origin) =>
+const environmentScenario = ({ endpoint, targetId, origin, values, run }) =>
   browserScenarioSchema.parse({
     browser: { mode: "connect", cdp_endpoint: endpoint, target_id: targetId },
-    start_url: { url: `${origin}/scenario-environment` },
+    start_url: {
+      url: `${origin}/scenario-environment${run === undefined ? "" : `?run=${run}`}`,
+    },
     environment: {
-      locale: expected.locale,
-      timezone: expected.timezone,
+      locale: values.locale,
+      timezone: values.timezone,
       viewport: {
-        width: expected.width,
-        height: expected.height,
-        device_scale_factor: expected.dpr,
+        width: values.width,
+        height: values.height,
+        device_scale_factor: values.dpr,
       },
     },
-    actions: [
-      {
-        step_id: "refresh",
-        action: "click",
-        locator: { kind: "css", selector: "#refresh-environment" },
-      },
-    ],
+    actions:
+      run === undefined
+        ? [
+            {
+              step_id: "refresh",
+              action: "click",
+              locator: { kind: "css", selector: "#refresh-environment" },
+            },
+          ]
+        : [
+            {
+              step_id: `gate_${run}`,
+              action: "wait_for",
+              locator: { kind: "css", selector: `#release-${run}` },
+              state: "attached",
+              timeout_ms: 30_000,
+            },
+            {
+              step_id: `refresh_${run}`,
+              action: "click",
+              locator: { kind: "css", selector: "#refresh-environment" },
+            },
+          ],
     capture: { after_each_step: ["dom"], at_end: ["dom"] },
   });
 
-const assertCapture = (capture) => {
+const assertCapture = (capture, values = expected) => {
   assert.equal(capture.browser.cleanup, "disconnected-external");
   for (const step of capture.steps) {
     assert.equal(step.artifacts.dom.state, "captured");
     const text = step.artifacts.dom.value.text;
     const observed = /
([^<]+)<\/pre>/u.exec(text);
     assert.ok(observed, "DOM omitted the page's actual environment values");
-    assert.deepEqual(JSON.parse(observed[1]), expected);
+    assert.deepEqual(JSON.parse(observed[1]), values);
   }
 };
 
@@ -75,7 +100,12 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
     return JSON.parse(value.result.value);
   };
   const baseline = await readEnvironment();
-  const scenario = environmentScenario(endpoint, targetId, origin);
+  const scenario = environmentScenario({
+    endpoint,
+    targetId,
+    origin,
+    values: expected,
+  });
   const assertRestored = async () => {
     assert.deepEqual(await readEnvironment(), baseline);
     const remaining = await (await fetch(`${endpoint}/json/list`)).json();
@@ -105,6 +135,15 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
           "capture_browser_scenario",
         ),
       );
+      await verifyConcurrentMcpCapture({
+        client,
+        connection,
+        endpoint,
+        targetId,
+        origin,
+        readEnvironment,
+        assertRestored,
+      });
     } finally {
       await client.close();
       await transport.close();
@@ -157,6 +196,125 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
   }
 }
 
+const verifyConcurrentMcpCapture = async ({
+  client,
+  connection,
+  endpoint,
+  targetId,
+  origin,
+  readEnvironment,
+  assertRestored,
+}) => {
+  const firstScenario = environmentScenario({
+    endpoint,
+    targetId,
+    origin,
+    values: expected,
+    run: "A",
+  });
+  const secondScenario = environmentScenario({
+    endpoint,
+    targetId,
+    origin,
+    values: alternate,
+    run: "B",
+  });
+  const firstCancellation = new AbortController();
+  const secondCancellation = new AbortController();
+  const cancellation = new AbortController();
+  const pendingCalls = [];
+  const callTool = (arguments_, signal) => {
+    const pending = client.callTool(
+      { name: "capture_browser_scenario", arguments: arguments_ },
+      { signal, timeout: 60_000 },
+    );
+    void pending.catch(() => {});
+    pendingCalls.push(pending);
+    return pending;
+  };
+
+  try {
+    const first = callTool(firstScenario, firstCancellation.signal);
+    await waitForEnvironment(readEnvironment, connection, expected, "A");
+
+    const second = callTool(secondScenario, secondCancellation.signal);
+    await client.ping();
+    assert.deepEqual(await readEnvironment(), expected);
+    assert.equal(await readScenarioRun(connection), "A");
+
+    const cancelled = callTool(
+      environmentScenario({
+        endpoint,
+        targetId,
+        origin,
+        values: alternate,
+        run: "C",
+      }),
+      cancellation.signal,
+    );
+    await client.ping();
+    cancellation.abort(new Error("cancel queued browser scenario"));
+    await assert.rejects(cancelled, /cancel queued browser scenario/u);
+    assert.deepEqual(await readEnvironment(), expected);
+    assert.equal(await readScenarioRun(connection), "A");
+
+    await releaseScenario(connection);
+    assertCapture(
+      requireMcpEvidenceResult(await first, "capture_browser_scenario"),
+      expected,
+    );
+
+    await waitForEnvironment(readEnvironment, connection, alternate, "B");
+    await releaseScenario(connection);
+    assertCapture(
+      requireMcpEvidenceResult(await second, "capture_browser_scenario"),
+      alternate,
+    );
+    await client.ping();
+    await assertRestored();
+  } finally {
+    firstCancellation.abort();
+    secondCancellation.abort();
+    cancellation.abort();
+    await releaseScenario(connection).catch(() => undefined);
+    await Promise.allSettled(pendingCalls);
+  }
+};
+
+const waitForEnvironment = async (
+  readEnvironment,
+  connection,
+  expectedValues,
+  run,
+) => {
+  const deadline = Date.now() + 10_000;
+  while (Date.now() < deadline) {
+    if (
+      JSON.stringify(await readEnvironment()) ===
+        JSON.stringify(expectedValues) &&
+      (await readScenarioRun(connection)) === run
+    )
+      return;
+    await delay(25);
+  }
+  throw new Error(`Scenario ${run} never reached its page-controlled gate`);
+};
+
+const readScenarioRun = async (connection) => {
+  const value = await connection.send("Runtime.evaluate", {
+    expression: "document.body.dataset.run ?? null",
+    returnByValue: true,
+  });
+  return value.result.value;
+};
+
+const releaseScenario = async (connection) => {
+  await connection.send("Runtime.evaluate", {
+    expression: "window.releaseScenario()",
+    returnByValue: true,
+  });
+};
+
 async function verifyCancelledEnvironment(
   provider,
   connection,
diff --git a/src/browser/PlaywrightBrowserScenarioProvider.test.ts b/src/browser/PlaywrightBrowserScenarioProvider.test.ts
index b66cecb20..af94b7f90 100644
--- a/src/browser/PlaywrightBrowserScenarioProvider.test.ts
+++ b/src/browser/PlaywrightBrowserScenarioProvider.test.ts
@@ -529,9 +529,11 @@ it("shares concurrent close and retries browser cleanup after failure", async ()
   const finishEvents = vi
     .fn<() => Promise>()
     .mockResolvedValue(undefined);
+  const cleanupSettlements: boolean[] = [];
   const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
     closeBrowser: browserClose,
     removeProfile,
+    onSettled: (browserClosed) => cleanupSettlements.push(browserClosed),
   });
 
   const first = cleanup.close(finishEvents);
@@ -541,12 +543,14 @@ it("shares concurrent close and retries browser cleanup after failure", async ()
   expect(browserClose).toHaveBeenCalledTimes(1);
   expect(removeProfile).not.toHaveBeenCalled();
   expect(finishEvents).toHaveBeenCalledTimes(1);
+  expect(cleanupSettlements).toEqual([false]);
 
   await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
   await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
   expect(browserClose).toHaveBeenCalledTimes(2);
   expect(removeProfile).toHaveBeenCalledTimes(1);
   expect(finishEvents).toHaveBeenCalledTimes(1);
+  expect(cleanupSettlements).toEqual([false, true]);
 });
 
 it("keeps failed event finalization failed across cleanup retries", async () => {
diff --git a/src/browser/PlaywrightScenarioBrowser.test.ts b/src/browser/PlaywrightScenarioBrowser.test.ts
index 970decfd9..4ee0a3f1f 100644
--- a/src/browser/PlaywrightScenarioBrowser.test.ts
+++ b/src/browser/PlaywrightScenarioBrowser.test.ts
@@ -1,4 +1,5 @@
 import { afterEach, expect, it, vi } from "vitest";
+import type { Browser } from "playwright-core";
 
 import { browserScenarioSchema } from "../domain/browserScenario.js";
 import {
@@ -8,6 +9,14 @@ import {
 
 afterEach(() => vi.unstubAllEnvs());
 
+const deferred = () => {
+  let resolve: (value: Value | PromiseLike) => void = () => undefined;
+  const promise = new Promise((resolvePromise) => {
+    resolve = resolvePromise;
+  });
+  return { promise, resolve };
+};
+
 it("passes the selected environment to the actual browser launch boundary", async () => {
   vi.stubEnv("LANG", "ambient-language");
   const selected = {
@@ -25,12 +34,14 @@ it("passes the selected environment to the actual browser launch boundary", asyn
   });
   await expect(
     openPlaywrightScenarioBrowser(scenario, selected, {
-      connectOverCDP: async () => {
-        throw new Error("Unexpected connection");
-      },
-      launchPersistentContext: async (_profile, options) => {
-        launchedEnvironment = options?.env;
-        throw new Error("launch boundary reached");
+      launcher: {
+        connectOverCDP: async () => {
+          throw new Error("Unexpected connection");
+        },
+        launchPersistentContext: async (_profile, options) => {
+          launchedEnvironment = options?.env;
+          throw new Error("launch boundary reached");
+        },
       },
     }),
   ).rejects.toThrow("launch boundary reached");
@@ -40,27 +51,244 @@ it("passes the selected environment to the actual browser launch boundary", asyn
   });
 });
 
-it("returns cancellation instead of success when an attached browser hangs on close", async () => {
+it("keeps attached-target ownership until cancelled cleanup actually settles", async () => {
   const controller = new AbortController();
-  let resolveCloseStarted: () => void = () => undefined;
-  const closeStarted = new Promise((resolve) => {
-    resolveCloseStarted = resolve;
-  });
+  const closeStarted = deferred();
+  const closeResult = deferred();
+  const settled: boolean[] = [];
   const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
     closeBrowser: () => {
-      resolveCloseStarted();
-      return new Promise(() => undefined);
+      closeStarted.resolve(undefined);
+      return closeResult.promise;
     },
     removeProfile: undefined,
+    onSettled: (browserClosed) => settled.push(browserClosed),
   });
-  const closing = cleanup.close(undefined, controller.signal);
-
-  await closeStarted;
+  const cancelledClose = cleanup.close(undefined, controller.signal);
+  await closeStarted.promise;
   controller.abort();
-  await expect(closing).rejects.toMatchObject({
+  await expect(cancelledClose).rejects.toMatchObject({
     _tag: "BrowserObservationError",
     reason: "cleanup_failed",
     cleanupIncomplete: true,
     userCategory: "cancelled",
   });
+  expect(settled).toEqual([]);
+
+  closeResult.resolve(undefined);
+  await cleanup.close();
+  expect(settled).toEqual([true]);
+});
+
+it("keeps attached-target ownership after the cleanup response timeout", async () => {
+  vi.useFakeTimers();
+  try {
+    const closeStarted = deferred();
+    const closeResult = deferred();
+    const settled: boolean[] = [];
+    const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
+      closeBrowser: () => {
+        closeStarted.resolve(undefined);
+        return closeResult.promise;
+      },
+      removeProfile: undefined,
+      onSettled: (browserClosed) => settled.push(browserClosed),
+    });
+    const timedOutClose = cleanup.close();
+    const timeoutExpectation = expect(timedOutClose).rejects.toMatchObject({
+      reason: "cleanup_failed",
+      cleanup: { reason: expect.stringContaining("timed out") },
+    });
+    await closeStarted.promise;
+    await vi.advanceTimersByTimeAsync(1_000);
+    await timeoutExpectation;
+    expect(settled).toEqual([]);
+
+    closeResult.resolve(undefined);
+    await cleanup.close();
+    expect(settled).toEqual([true]);
+  } finally {
+    vi.useRealTimers();
+  }
+});
+
+it("does not configure a late attached connection after cancellation", async () => {
+  const connection =
+    deferred>();
+  const connectionStarted = deferred();
+  const connectedBrowser = {
+    close: vi.fn(async () => undefined),
+    contexts: vi.fn(() => []),
+    version: () => "fixture",
+  };
+  const controller = new AbortController();
+  const launcher = {
+    connectOverCDP: () => {
+      connectionStarted.resolve(undefined);
+      return connection.promise;
+    },
+    launchPersistentContext: async () => {
+      throw new Error("Unexpected launch");
+    },
+  };
+  const scenario = browserScenarioSchema.parse({
+    browser: {
+      mode: "connect",
+      cdp_endpoint: "http://127.0.0.1:9222",
+      target_id: "page-1",
+    },
+    start_url: { url: "https://example.test" },
+    actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
+  });
+  const opening = openPlaywrightScenarioBrowser(
+    scenario,
+    {},
+    {
+      launcher,
+      signal: controller.signal,
+    },
+  );
+  await connectionStarted.promise;
+  controller.abort();
+  connection.resolve(connectedBrowser);
+
+  await expect(opening).rejects.toMatchObject({
+    _tag: "BrowserObservationError",
+    reason: "cancelled",
+  });
+  expect(connectedBrowser.contexts).not.toHaveBeenCalled();
+  expect(connectedBrowser.close).toHaveBeenCalledOnce();
+});
+
+it("closes an attached connection when cancellation starts target discovery", async () => {
+  const controller = new AbortController();
+  const connectedBrowser = {
+    close: vi.fn(async () => undefined),
+    contexts: vi.fn(() => {
+      controller.abort();
+      return [];
+    }),
+    version: () => "fixture",
+  };
+  const launcher = {
+    connectOverCDP: async () => connectedBrowser,
+    launchPersistentContext: async () => {
+      throw new Error("Unexpected launch");
+    },
+  };
+  const scenario = browserScenarioSchema.parse({
+    browser: {
+      mode: "connect",
+      cdp_endpoint: "http://127.0.0.1:9222",
+      target_id: "page-1",
+    },
+    start_url: { url: "https://example.test" },
+    actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
+  });
+
+  await expect(
+    openPlaywrightScenarioBrowser(
+      scenario,
+      {},
+      {
+        launcher,
+        signal: controller.signal,
+      },
+    ),
+  ).rejects.toMatchObject({
+    _tag: "AnalysisCancelledError",
+  });
+  expect(connectedBrowser.contexts).toHaveBeenCalledOnce();
+  expect(connectedBrowser.close).toHaveBeenCalledOnce();
+});
+
+it("cancels same-target queued connection before acquiring a browser", async () => {
+  const makeScenario = (targetId: string) =>
+    browserScenarioSchema.parse({
+      browser: {
+        mode: "connect",
+        cdp_endpoint: "http://127.0.0.1:9222",
+        target_id: targetId,
+      },
+      start_url: { url: "https://example.test" },
+      actions: [
+        {
+          step_id: "wait",
+          action: "wait_for_timeout",
+          duration_ms: 1,
+        },
+      ],
+    });
+  let rejectFirst: ((cause: Error) => void) | undefined;
+  const firstConnection = new Promise((_resolve, reject) => {
+    rejectFirst = reject;
+  });
+  let resolveFirstStarted: (() => void) | undefined;
+  const firstStarted = new Promise((resolve) => {
+    resolveFirstStarted = resolve;
+  });
+  const endpoints: string[] = [];
+  const connectOverCDP = vi.fn((endpoint: string) => {
+    endpoints.push(endpoint);
+    if (endpoints.length === 1) {
+      resolveFirstStarted?.();
+      return firstConnection;
+    }
+    return Promise.reject(new Error("connection failed"));
+  });
+  const launchPersistentContext = vi.fn(async () => {
+    throw new Error("launch boundary reached");
+  });
+  const launcher = { connectOverCDP, launchPersistentContext };
+  const environment = {};
+  const first = openPlaywrightScenarioBrowser(
+    makeScenario("page-1"),
+    environment,
+    { launcher },
+  );
+  await firstStarted;
+  expect(connectOverCDP).toHaveBeenCalledTimes(1);
+
+  const controller = new AbortController();
+  const removeAbort = vi.spyOn(controller.signal, "removeEventListener");
+  const queued = openPlaywrightScenarioBrowser(
+    makeScenario("page-1"),
+    environment,
+    { launcher, signal: controller.signal },
+  );
+  controller.abort();
+  await expect(queued).rejects.toMatchObject({
+    _tag: "BrowserObservationError",
+    reason: "cancelled",
+  });
+  expect(connectOverCDP).toHaveBeenCalledTimes(1);
+  expect(removeAbort).toHaveBeenCalledWith("abort", expect.any(Function));
+
+  await expect(
+    openPlaywrightScenarioBrowser(makeScenario("page-2"), environment, {
+      launcher,
+    }),
+  ).rejects.toThrow("connection failed");
+  expect(connectOverCDP).toHaveBeenCalledTimes(2);
+
+  const launch = browserScenarioSchema.parse({
+    browser: { mode: "launch", executable_path: process.execPath },
+    start_url: { url: "https://example.test" },
+    actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
+  });
+  await expect(
+    openPlaywrightScenarioBrowser(launch, environment, { launcher }),
+  ).rejects.toThrow("launch boundary reached");
+  expect(launchPersistentContext).toHaveBeenCalledTimes(1);
+
+  if (rejectFirst === undefined)
+    throw new Error("first connection did not begin");
+  rejectFirst(new Error("first connection failed"));
+  await expect(first).rejects.toThrow("first connection failed");
+  await expect(
+    openPlaywrightScenarioBrowser(makeScenario("page-1"), environment, {
+      launcher,
+    }),
+  ).rejects.toThrow("connection failed");
+  expect(connectOverCDP).toHaveBeenCalledTimes(3);
 });
diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts
index 392c96278..88fdda0f8 100644
--- a/src/browser/PlaywrightScenarioBrowser.ts
+++ b/src/browser/PlaywrightScenarioBrowser.ts
@@ -16,10 +16,15 @@ import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.j
 
 const OPERATION = "capture_browser_scenario" as const;
 
+const throwIfScenarioCancelled = (signal: AbortSignal | undefined): void => {
+  if (signal?.aborted === true)
+    throw new BrowserObservationError(OPERATION, "cancelled");
+};
+
 export interface OpenedScenarioBrowser {
   readonly context: BrowserContext;
   readonly page: Page;
-  readonly browser: Browser;
+  readonly browser: Pick;
   readonly profilePath: string | undefined;
   readonly cleanup: PlaywrightScenarioBrowserCleanupOwner;
 }
@@ -28,6 +33,7 @@ export interface OpenedScenarioBrowser {
 interface PlaywrightScenarioCleanupResources {
   readonly closeBrowser: () => Promise;
   readonly removeProfile: (() => Promise) | undefined;
+  readonly onSettled?: (browserClosed: boolean) => void;
 }
 
 /** Owns one browser connection and optional private profile through cleanup retries. */
@@ -49,9 +55,13 @@ export class PlaywrightScenarioBrowserCleanupOwner {
     const cleanup = this.#closePromise ?? this.#closeResources(finishEvents);
     if (this.#closePromise === undefined) {
       this.#closePromise = cleanup;
-      void cleanup.catch(() => {
-        if (this.#closePromise === cleanup) this.#closePromise = undefined;
-      });
+      void cleanup.then(
+        () => this.resources.onSettled?.(this.#browserClosed),
+        () => {
+          if (this.#closePromise === cleanup) this.#closePromise = undefined;
+          this.resources.onSettled?.(this.#browserClosed);
+        },
+      );
     }
     return this.#awaitCleanup(cleanup, signal);
   }
@@ -115,6 +125,116 @@ export class PlaywrightScenarioBrowserCleanupOwner {
   }
 }
 
+interface AttachedScenarioWaiter {
+  readonly signal: AbortSignal | undefined;
+  readonly resolve: (release: () => void) => void;
+  readonly reject: (error: BrowserObservationError) => void;
+  onAbort: (() => void) | undefined;
+}
+
+interface AttachedScenarioAdmission {
+  active: boolean;
+  readonly waiters: AttachedScenarioWaiter[];
+  cleanupOwner: PlaywrightScenarioBrowserCleanupOwner | undefined;
+}
+
+interface AttachedScenarioLease {
+  readonly admission: AttachedScenarioAdmission;
+  readonly release: () => void;
+}
+
+const attachedScenarioAdmissions = new Map();
+
+const releaseAttachedScenario = (
+  key: string,
+  admission: AttachedScenarioAdmission,
+): void => {
+  const waiter = admission.waiters.shift();
+  if (waiter === undefined) {
+    admission.active = false;
+    if (
+      admission.cleanupOwner === undefined &&
+      attachedScenarioAdmissions.get(key) === admission
+    )
+      attachedScenarioAdmissions.delete(key);
+    return;
+  }
+
+  if (waiter.onAbort !== undefined)
+    waiter.signal?.removeEventListener("abort", waiter.onAbort);
+  if (waiter.signal?.aborted === true) {
+    waiter.reject(new BrowserObservationError(OPERATION, "cancelled"));
+    releaseAttachedScenario(key, admission);
+    return;
+  }
+  waiter.resolve(createAttachedScenarioRelease(key, admission));
+};
+
+const createAttachedScenarioRelease = (
+  key: string,
+  admission: AttachedScenarioAdmission,
+): (() => void) => {
+  let released = false;
+  return () => {
+    if (released) return;
+    released = true;
+    releaseAttachedScenario(key, admission);
+  };
+};
+
+const acquireAttachedScenario = (
+  scenario: Extract,
+  signal: AbortSignal | undefined,
+): Promise => {
+  if (signal?.aborted === true)
+    return Promise.reject(new BrowserObservationError(OPERATION, "cancelled"));
+
+  const key = JSON.stringify([scenario.cdp_endpoint, scenario.target_id]);
+  const admission =
+    attachedScenarioAdmissions.get(key) ??
+    ({
+      active: false,
+      waiters: [],
+      cleanupOwner: undefined,
+    } satisfies AttachedScenarioAdmission);
+  attachedScenarioAdmissions.set(key, admission);
+
+  return new Promise((resolve, reject) => {
+    const grant = (release: () => void): void =>
+      resolve({ admission, release });
+    if (!admission.active) {
+      admission.active = true;
+      grant(createAttachedScenarioRelease(key, admission));
+      return;
+    }
+
+    const waiter: AttachedScenarioWaiter = {
+      signal,
+      resolve: (release) => grant(release),
+      reject,
+      onAbort: undefined,
+    };
+    admission.waiters.push(waiter);
+    if (signal !== undefined) {
+      const onAbort = (): void => {
+        const index = admission.waiters.indexOf(waiter);
+        if (index < 0) return;
+        admission.waiters.splice(index, 1);
+        signal.removeEventListener("abort", onAbort);
+        reject(new BrowserObservationError(OPERATION, "cancelled"));
+        if (!admission.active && admission.waiters.length === 0)
+          releaseAttachedScenario(key, admission);
+      };
+      waiter.onAbort = onAbort;
+      signal.addEventListener("abort", onAbort, { once: true });
+      if (signal.aborted) {
+        onAbort();
+        return;
+      }
+    }
+  });
+};
+
 const allowedBrowserEnvironment = (
   environment: Readonly>,
 ): Record => {
@@ -142,14 +262,17 @@ const allowedBrowserEnvironment = (
   );
 };
 const findConnectedPage = async (
-  browser: Browser,
+  browser: Pick,
   targetId: string,
+  signal: AbortSignal | undefined,
 ): Promise<{ readonly context: BrowserContext; readonly page: Page }> => {
   for (const context of browser.contexts())
     for (const page of context.pages()) {
       const session = await context.newCDPSession(page);
       try {
+        throwIfScenarioCancelled(signal);
         const { targetInfo } = await session.send("Target.getTargetInfo");
+        throwIfScenarioCancelled(signal);
         if (targetInfo.targetId !== targetId) continue;
         return { context, page };
       } finally {
@@ -162,30 +285,36 @@ const findConnectedPage = async (
 const configureAttachedEnvironment = async (
   context: BrowserContext,
   page: Page,
-  scenario: BrowserScenario,
+  environment: BrowserScenario["environment"],
+  signal: AbortSignal | undefined,
 ): Promise => {
   await page.setViewportSize({
-    width: scenario.environment.viewport.width,
-    height: scenario.environment.viewport.height,
+    width: environment.viewport.width,
+    height: environment.viewport.height,
   });
+  throwIfScenarioCancelled(signal);
   await page.emulateMedia({
-    colorScheme: scenario.environment.color_scheme,
-    reducedMotion: scenario.environment.reduced_motion,
+    colorScheme: environment.color_scheme,
+    reducedMotion: environment.reduced_motion,
   });
+  throwIfScenarioCancelled(signal);
   const session = await context.newCDPSession(page);
+  throwIfScenarioCancelled(signal);
   // Chromium resets these overrides when the CDP session detaches. Keep it on
   // the scenario transport until cleanup disconnects the attached browser.
   await session.send("Emulation.setDeviceMetricsOverride", {
-    width: scenario.environment.viewport.width,
-    height: scenario.environment.viewport.height,
-    deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
+    width: environment.viewport.width,
+    height: environment.viewport.height,
+    deviceScaleFactor: environment.viewport.device_scale_factor,
     mobile: false,
   });
+  throwIfScenarioCancelled(signal);
   await session.send("Emulation.setLocaleOverride", {
-    locale: scenario.environment.locale,
+    locale: environment.locale,
   });
+  throwIfScenarioCancelled(signal);
   await session.send("Emulation.setTimezoneOverride", {
-    timezoneId: scenario.environment.timezone,
+    timezoneId: environment.timezone,
   });
 };
 
@@ -224,40 +353,97 @@ export const failBrowserScenarioOperation = async (
   throw primaryFailure;
 };
 
+type ScenarioBrowserLauncher = Pick<
+  typeof chromium,
+  "launchPersistentContext"
+> & {
+  readonly connectOverCDP: (
+    endpoint: string,
+  ) => Promise>;
+};
+
+type AttachedBrowserRequest = Extract<
+  BrowserScenario["browser"],
+  { readonly mode: "connect" }
+>;
+
+const openAttachedScenarioBrowser = async (
+  browserRequest: AttachedBrowserRequest,
+  environment: BrowserScenario["environment"],
+  launcher: ScenarioBrowserLauncher,
+  signal: AbortSignal | undefined,
+): Promise => {
+  const lease = await acquireAttachedScenario(browserRequest, signal);
+  let cleanupOwner: PlaywrightScenarioBrowserCleanupOwner | undefined;
+  try {
+    const priorOwner = lease.admission.cleanupOwner;
+    if (priorOwner !== undefined) await priorOwner.close();
+    throwIfScenarioCancelled(signal);
+
+    const browser = await launcher.connectOverCDP(browserRequest.cdp_endpoint);
+    const cleanup: PlaywrightScenarioBrowserCleanupOwner =
+      new PlaywrightScenarioBrowserCleanupOwner({
+        closeBrowser: () => browser.close(),
+        onSettled: (browserClosed) => {
+          if (browserClosed && lease.admission.cleanupOwner === cleanup)
+            lease.admission.cleanupOwner = undefined;
+          lease.release();
+        },
+        removeProfile: undefined,
+      });
+    cleanupOwner = cleanup;
+    lease.admission.cleanupOwner = cleanup;
+    throwIfScenarioCancelled(signal);
+    const target = await withPlaywrightExecutionBoundary(
+      () => findConnectedPage(browser, browserRequest.target_id, signal),
+      undefined,
+      signal,
+    );
+    throwIfScenarioCancelled(signal);
+    await withPlaywrightExecutionBoundary(
+      () =>
+        configureAttachedEnvironment(
+          target.context,
+          target.page,
+          environment,
+          signal,
+        ),
+      undefined,
+      signal,
+    );
+    return {
+      ...target,
+      browser,
+      profilePath: undefined,
+      cleanup,
+    };
+  } catch (cause: unknown) {
+    if (cleanupOwner === undefined) {
+      lease.release();
+      throw cause;
+    }
+    const cleanup = cleanupOwner;
+    return failBrowserScenarioOperation(() => cleanup.close(), cause);
+  }
+};
+
 /** Launch or attach using the caller-selected environment and browser engine. */
 export const openPlaywrightScenarioBrowser = async (
   scenario: BrowserScenario,
   environment: Readonly>,
-  launcher: Pick<
-    typeof chromium,
-    "connectOverCDP" | "launchPersistentContext"
-  > = chromium,
+  options: {
+    readonly launcher?: ScenarioBrowserLauncher;
+    readonly signal?: AbortSignal | undefined;
+  } = {},
 ): Promise => {
-  if (scenario.browser.mode === "connect") {
-    const browser = await launcher.connectOverCDP(
-      scenario.browser.cdp_endpoint,
-      { timeout: 0 },
+  const launcher = options.launcher ?? chromium;
+  if (scenario.browser.mode === "connect")
+    return openAttachedScenarioBrowser(
+      scenario.browser,
+      scenario.environment,
+      launcher,
+      options.signal,
     );
-    const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
-      closeBrowser: () => browser.close(),
-      removeProfile: undefined,
-    });
-    try {
-      const target = await findConnectedPage(
-        browser,
-        scenario.browser.target_id,
-      );
-      await configureAttachedEnvironment(target.context, target.page, scenario);
-      return {
-        ...target,
-        browser,
-        profilePath: undefined,
-        cleanup,
-      };
-    } catch (cause: unknown) {
-      return failBrowserScenarioOperation(() => cleanup.close(), cause);
-    }
-  }
 
   const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
   let context: BrowserContext;
diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.ts
index 26aa65fcd..c4ac54459 100644
--- a/src/browser/PlaywrightScenarioSession.ts
+++ b/src/browser/PlaywrightScenarioSession.ts
@@ -135,7 +135,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
     if (secrets === undefined)
       throw new BrowserObservationError(OPERATION, "secret_unavailable");
     const startedAt = Date.now();
-    const opening = openPlaywrightScenarioBrowser(scenario, environment);
+    const opening = openPlaywrightScenarioBrowser(scenario, environment, {
+      signal: options.signal,
+    });
     let opened: OpenedScenarioBrowser;
     let events: PlaywrightScenarioEvents | undefined;
     try {

From 5f16124a31fa4a82bd03037506809d6be959d768 Mon Sep 17 00:00:00 2001
From: You Wish <29498139+Y0UW1SH@users.noreply.github.com>
Date: Fri, 9 Oct 2026 13:49:54 -0400
Subject: [PATCH 047/189] fix(files): reject nonregular capture and JSON inputs

Verify selected files through a nonblocking opened handle before reading. Preserve regular-file symlinks and return actionable CLI/MCP diagnostics without publishing output.

Co-authored-by: YouWish <29498139+Y0UW1SH@users.noreply.github.com>
---
 docs/javascript-application-workflows.md      |   4 +
 docs/website-script-export.md                 |   4 +
 src/application/RegularFileRead.ts            |  42 ++++++
 src/application/WebScriptExportService.ts     |  20 ++-
 .../android/AndroidAnalysisService.ts         |   7 +-
 src/cliJsonInput.ts                           |  14 +-
 .../cli/webScriptSelectionCli.test.ts         |  46 +++++++
 .../boundary/filesystem/cliJsonInput.test.ts  |  80 ++++++++++-
 .../filesystem/webScriptExport.test.ts        | 125 ++++++++++++++++++
 .../mcp/webScriptSelectionMcp.test.ts         |  78 +++++++++++
 tests/fixtures/fifoInput.ts                   |  36 +++++
 11 files changed, 442 insertions(+), 14 deletions(-)
 create mode 100644 src/application/RegularFileRead.ts
 create mode 100644 tests/boundary/cli/webScriptSelectionCli.test.ts
 create mode 100644 tests/boundary/mcp/webScriptSelectionMcp.test.ts
 create mode 100644 tests/fixtures/fifoInput.ts

diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md
index 5ff388626..63be6935f 100644
--- a/docs/javascript-application-workflows.md
+++ b/docs/javascript-application-workflows.md
@@ -175,6 +175,10 @@ All five CLI commands accept inline JSON or a path to a JSON file. The CLI
 returns an Evidence record directly. Put the full records in a later CLI input;
 a separate CLI process has no retained MCP connection state.
 
+File inputs must be regular files; symlinks to regular files are accepted.
+Directories, named pipes and device files produce an input error before JSON
+parsing.
+
 For a literal string trace, analyze your supplied tree once, then build the
 input from the saved Evidence (replace the target and seed):
 
diff --git a/docs/website-script-export.md b/docs/website-script-export.md
index 3745ff9ae..31ffaff45 100644
--- a/docs/website-script-export.md
+++ b/docs/website-script-export.md
@@ -12,6 +12,10 @@ For passive inspection, select `include_script_sources: true` (CLI:
 `capture.network.response_body: true`. Save either the complete Evidence record
 or its normalized result as UTF-8 JSON. MCP `structuredContent` contains the complete Evidence record.
 
+The capture must be a regular file. A symlink to a regular file is accepted;
+directories, named pipes and device files are rejected before reading capture
+bytes or creating output.
+
 ```sh
 rea export-web-scripts /analysis/capture.json /analysis/exported-scripts --json
 rea analyze-javascript-application /analysis/exported-scripts/files --json
diff --git a/src/application/RegularFileRead.ts b/src/application/RegularFileRead.ts
new file mode 100644
index 000000000..c5ad5f9e3
--- /dev/null
+++ b/src/application/RegularFileRead.ts
@@ -0,0 +1,42 @@
+import { constants } from "node:fs";
+import { open } from "node:fs/promises";
+
+/** The opened input cannot supply regular-file bytes. */
+export class NonRegularFileReadError extends Error {
+  readonly code: "EISDIR" | "ENOTFILE";
+
+  constructor(
+    readonly path: string,
+    directory: boolean,
+  ) {
+    super(`Selected input must be a regular file: ${path}`);
+    this.name = "NonRegularFileReadError";
+    this.code = directory ? "EISDIR" : "ENOTFILE";
+  }
+}
+
+/** Admit a regular file without waiting for a pipe, then read its verified handle. */
+export const readRegularFile = async (
+  path: string,
+  signal?: AbortSignal,
+): Promise => {
+  signal?.throwIfAborted();
+  const handle = await open(
+    path,
+    constants.O_RDONLY |
+      (constants.O_NONBLOCK ?? 0) |
+      (constants.O_NOCTTY ?? 0),
+  );
+  try {
+    signal?.throwIfAborted();
+    const stats = await handle.stat();
+    signal?.throwIfAborted();
+    if (!stats.isFile())
+      throw new NonRegularFileReadError(path, stats.isDirectory());
+    const bytes = await handle.readFile({ signal });
+    signal?.throwIfAborted();
+    return bytes;
+  } finally {
+    await handle.close();
+  }
+};
diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts
index d35341f43..dfe54bb8e 100644
--- a/src/application/WebScriptExportService.ts
+++ b/src/application/WebScriptExportService.ts
@@ -1,5 +1,4 @@
 import { createHash } from "node:crypto";
-import { readFile } from "node:fs/promises";
 import { isAbsolute } from "node:path";
 
 import { z } from "zod";
@@ -27,6 +26,7 @@ import {
 import { WebScriptExportError } from "../domain/webScriptExportError.js";
 import type { ExecutionOptions } from "./AnalysisProvider.js";
 import { WEB_SCRIPT_EXPORT_PROVIDER as PROVIDER } from "./InvestigationProviders.js";
+import { NonRegularFileReadError, readRegularFile } from "./RegularFileRead.js";
 
 const OPERATION = "export_web_scripts";
 
@@ -152,7 +152,7 @@ const readCapture = async (
   signal: AbortSignal | undefined,
 ): Promise> => {
   try {
-    return ok(await readFile(path, { signal }));
+    return ok(await readRegularFile(path, signal));
   } catch (cause: unknown) {
     const code =
       cause instanceof Error && "code" in cause ? String(cause.code) : "";
@@ -160,16 +160,24 @@ const readCapture = async (
       return err(
         new AnalysisAccessDeniedError(OPERATION, path, code, { cause }),
       );
-    if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR")
+    if (
+      cause instanceof NonRegularFileReadError ||
+      code === "ENOENT" ||
+      code === "ENOTDIR" ||
+      code === "EISDIR" ||
+      code === "ENXIO"
+    )
       return err(
         new AnalysisInputError(OPERATION, { cause }, [
           {
             path: ["capture_path"],
             reason: "invalid_value",
             message:
-              code === "EISDIR"
-                ? `Selected capture is a directory, not a file: ${path}`
-                : `Selected capture could not be read (${code}): ${path}`,
+              cause instanceof NonRegularFileReadError && code !== "EISDIR"
+                ? cause.message
+                : code === "EISDIR"
+                  ? `Selected capture is a directory, not a file: ${path}`
+                  : `Selected capture could not be read (${code}): ${path}`,
           },
         ]),
       );
diff --git a/src/application/android/AndroidAnalysisService.ts b/src/application/android/AndroidAnalysisService.ts
index a126df57c..eae2efb8d 100644
--- a/src/application/android/AndroidAnalysisService.ts
+++ b/src/application/android/AndroidAnalysisService.ts
@@ -29,9 +29,10 @@ export class AndroidAnalysisService {
     const request = androidRequestSchema.safeParse({ operation, input });
     if (!request.success)
       return err(new AnalysisInputError(operation, { cause: request.error }));
-    const target = await parseBinaryTarget(request.data.input.path, {
-      ...(options?.signal === undefined ? {} : { signal: options.signal }),
-    });
+    const target = await parseBinaryTarget(
+      request.data.input.path,
+      options?.signal === undefined ? {} : { signal: options.signal },
+    );
     if (!target.ok) return target;
     const executed = await this.provider.execute(
       target.value,
diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts
index 9081b875e..5c4397bf6 100644
--- a/src/cliJsonInput.ts
+++ b/src/cliJsonInput.ts
@@ -1,6 +1,9 @@
-import { readFile } from "node:fs/promises";
 import { resolve } from "node:path";
 
+import {
+  NonRegularFileReadError,
+  readRegularFile,
+} from "./application/RegularFileRead.js";
 import { AnalysisInputError } from "./domain/analysisErrorCore.js";
 import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
 import type { JsonValue } from "./domain/jsonValue.js";
@@ -19,7 +22,7 @@ export const parseCliJsonInput = async (
   try {
     // Read raw bytes so invalid UTF-8 is rejected by parseJson instead of
     // being silently replaced by lossy "utf8" decoding.
-    const parsed = parseJson(await readFile(value));
+    const parsed = parseJson(await readRegularFile(value));
     return parsed === undefined
       ? jsonFileError(value, operation, "invalid-json")
       : { ok: true, value: parsed };
@@ -136,7 +139,7 @@ const jsonFileError = (
   },
 });
 
-/** Name the system error so the caller can tell a typo from a permission denial. */
+/** Preserve file-selection and system failures alongside the requested path. */
 const readFailureIssue = (path: string | undefined, cause: unknown) => {
   const code =
     typeof cause === "object" &&
@@ -148,6 +151,9 @@ const readFailureIssue = (path: string | undefined, cause: unknown) => {
   return {
     path: [],
     reason: "invalid_value" as const,
-    message: `The JSON input file could not be read${code}: ${path ?? ""}`,
+    message:
+      cause instanceof NonRegularFileReadError && cause.code === "ENOTFILE"
+        ? `The JSON input must be a regular file${code}: ${path ?? ""}`
+        : `The JSON input file could not be read${code}: ${path ?? ""}`,
   };
 };
diff --git a/tests/boundary/cli/webScriptSelectionCli.test.ts b/tests/boundary/cli/webScriptSelectionCli.test.ts
new file mode 100644
index 000000000..416c81ac1
--- /dev/null
+++ b/tests/boundary/cli/webScriptSelectionCli.test.ts
@@ -0,0 +1,46 @@
+import { access } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect } from "vitest";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+cliTest.skipIf(process.platform === "win32")(
+  "exits with a capture_path invalid_request for a named pipe before publishing output",
+  async ({ cli, processes }) => {
+    const root = await createTestTempDirectory("rea-script-selection-cli-");
+    const capturePath = join(root, "capture.pipe");
+    const outputDirectory = join(root, "export");
+    const created = await processes.run("mkfifo", [capturePath], {
+      timeoutMs: 5_000,
+    });
+    expect(created.exitCode).toBe(0);
+
+    const response = await cli.run({
+      arguments: ["export-web-scripts", capturePath, outputDirectory, "--json"],
+      environment: { REA_LOG_LEVEL: "silent" },
+      timeoutMs: 5_000,
+    });
+    expect(response.exitCode).toBe(1);
+    expect(response.signal).toBeNull();
+    expect(response.json).toMatchObject({
+      error: "Script export failed",
+      code: "invalid_request",
+      details: {
+        operation: "export_web_scripts",
+        issues: [
+          {
+            path: ["capture_path"],
+            reason: "invalid_value",
+            message: expect.stringContaining("regular file"),
+          },
+        ],
+      },
+    });
+    expect(response.stdout).toContain(capturePath);
+    await expect(access(outputDirectory)).rejects.toMatchObject({
+      code: "ENOENT",
+    });
+  },
+);
diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts
index 1095840e0..d75dac4e3 100644
--- a/tests/boundary/filesystem/cliJsonInput.test.ts
+++ b/tests/boundary/filesystem/cliJsonInput.test.ts
@@ -1,11 +1,89 @@
-import { chmod, writeFile } from "node:fs/promises";
+import { execFile } from "node:child_process";
+import { chmod, symlink, writeFile } from "node:fs/promises";
 import { join } from "node:path";
+import { promisify } from "node:util";
 
 import { describe, expect, it, onTestFinished } from "vitest";
 
 import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
+import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
 
+describe("CLI JSON file selection", () => {
+  it("accepts a symlink to a regular JSON file", async () => {
+    const root = await createTestTempDirectory("rea-json-input-symlink-");
+    const path = join(root, "input.json");
+    const selected = join(root, "selected.json");
+    await writeFile(path, '{"value":1}');
+    await symlink(path, selected, "file");
+    expect(await parseCliJsonInput(selected, "test-input")).toEqual({
+      ok: true,
+      value: { value: 1 },
+    });
+  });
+
+  it
+    .skipIf(process.platform === "win32")
+    .each(["a named pipe", "a symlink to a named pipe"])(
+    "rejects %s without waiting for a writer",
+    async (kind) => {
+      const root = await createTestTempDirectory("rea-json-input-fifo-");
+      const fifoPath = join(root, "input.pipe");
+      await promisify(execFile)("mkfifo", [fifoPath]);
+      const selected =
+        kind === "a named pipe" ? fifoPath : join(root, "selected.json");
+      if (selected !== fifoPath) await symlink(fifoPath, selected, "file");
+
+      const outcome = await readWithoutFifoWriter(fifoPath, () =>
+        parseCliJsonInput(selected, "test-input"),
+      );
+      expect(outcome.state).toBe("completed");
+      if (outcome.state !== "completed")
+        throw new Error("JSON read waited for a FIFO writer");
+      expect(outcome.result).toMatchObject({
+        ok: false,
+        error: {
+          code: "invalid_request",
+          input_path: selected,
+          input_reason: "read-failed",
+          details: {
+            issues: [
+              {
+                path: [],
+                reason: "invalid_value",
+                message: expect.stringContaining("(ENOTFILE)"),
+              },
+            ],
+          },
+        },
+      });
+    },
+  );
+
+  it.skipIf(process.platform === "win32")(
+    "rejects a character device before parsing JSON bytes",
+    async () => {
+      expect(await parseCliJsonInput("/dev/null", "test-input")).toMatchObject({
+        ok: false,
+        error: {
+          code: "invalid_request",
+          input_path: "/dev/null",
+          input_reason: "read-failed",
+          details: {
+            issues: [
+              {
+                path: [],
+                reason: "invalid_value",
+                message: expect.stringContaining("(ENOTFILE)"),
+              },
+            ],
+          },
+        },
+      });
+    },
+  );
+});
+
 describe("CLI JSON input", () => {
   it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => {
     expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
diff --git a/tests/boundary/filesystem/webScriptExport.test.ts b/tests/boundary/filesystem/webScriptExport.test.ts
index ebc13ca48..3a6ce47fd 100644
--- a/tests/boundary/filesystem/webScriptExport.test.ts
+++ b/tests/boundary/filesystem/webScriptExport.test.ts
@@ -1,3 +1,4 @@
+import { execFile } from "node:child_process";
 import { createHash } from "node:crypto";
 import {
   access,
@@ -9,6 +10,7 @@ import {
   writeFile,
 } from "node:fs/promises";
 import { join } from "node:path";
+import { promisify } from "node:util";
 
 import { describe, expect, it, onTestFinished } from "vitest";
 
@@ -19,6 +21,7 @@ import { selectScriptCapture } from "../../../src/browser/assets/ScriptCaptureAd
 import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
 import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
 import { webScriptExportResultSchema } from "../../../src/domain/webScriptExport.js";
+import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
 import {
   scriptCaptureEvidenceFixture,
@@ -272,6 +275,128 @@ describe("captured script publication failures and cleanup", () => {
 });
 
 describe("captured script selection failures", () => {
+  it("accepts a capture symlink to a regular file and preserves its selected path", async () => {
+    const { root, input } = await setup();
+    const selected = join(root, "selected-capture.json");
+    await symlink(input.capture_path, selected, "file");
+
+    const result = await exportWebScripts({ ...input, capture_path: selected });
+    if (!result.ok) throw result.error;
+    expect(result.value.subject?.local_path).toBe(selected);
+    expect(
+      webScriptExportResultSchema.parse(result.value.normalized_result)
+        .capture_sha256,
+    ).toBe(
+      createHash("sha256")
+        .update(await readFile(input.capture_path))
+        .digest("hex"),
+    );
+    await expect(
+      access(join(input.output_directory, "manifest.json")),
+    ).resolves.toBeUndefined();
+  });
+
+  it
+    .skipIf(process.platform === "win32")
+    .each(["a named pipe", "a symlink to a named pipe"])(
+    "rejects %s without waiting for a writer or creating output",
+    async (kind) => {
+      const { root, input } = await setup();
+      const fifoPath = join(root, "capture.pipe");
+      await promisify(execFile)("mkfifo", [fifoPath]);
+      const selected =
+        kind === "a named pipe"
+          ? fifoPath
+          : join(root, "selected-capture.json");
+      if (selected !== fifoPath) await symlink(fifoPath, selected, "file");
+
+      const outcome = await readWithoutFifoWriter(fifoPath, () =>
+        exportWebScripts({ ...input, capture_path: selected }),
+      );
+      expect(outcome.state).toBe("completed");
+      if (outcome.state !== "completed")
+        throw new Error("Capture read waited for a FIFO writer");
+      if (outcome.result.ok)
+        throw new Error("Expected invalid capture selection");
+      expect(projectAnalysisError(outcome.result.error)).toMatchObject({
+        code: "invalid_request",
+        details: {
+          issues: [
+            {
+              path: ["capture_path"],
+              reason: "invalid_value",
+              message: expect.stringContaining("regular file"),
+            },
+          ],
+        },
+      });
+      expect(
+        JSON.stringify(projectAnalysisError(outcome.result.error)),
+      ).toContain(selected);
+      await expect(access(input.output_directory)).rejects.toMatchObject({
+        code: "ENOENT",
+      });
+    },
+  );
+
+  it.skipIf(process.platform === "win32")(
+    "rejects a character device as a capture selection before parsing bytes",
+    async () => {
+      const { input } = await setup();
+      const result = await exportWebScripts({
+        ...input,
+        capture_path: "/dev/null",
+      });
+      if (result.ok) throw new Error("Expected invalid capture selection");
+      expect(projectAnalysisError(result.error)).toMatchObject({
+        code: "invalid_request",
+        details: {
+          issues: [
+            {
+              path: ["capture_path"],
+              reason: "invalid_value",
+              message: expect.stringContaining("regular file"),
+            },
+          ],
+        },
+      });
+      expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
+        "/dev/null",
+      );
+      await expect(access(input.output_directory)).rejects.toMatchObject({
+        code: "ENOENT",
+      });
+    },
+  );
+
+  it.skipIf(process.platform === "win32")(
+    "honors a pre-aborted capture export before opening a named pipe",
+    async () => {
+      const { root, input } = await setup();
+      const fifoPath = join(root, "capture.pipe");
+      await promisify(execFile)("mkfifo", [fifoPath]);
+      const controller = new AbortController();
+      controller.abort();
+
+      const outcome = await readWithoutFifoWriter(fifoPath, () =>
+        exportWebScripts(
+          { ...input, capture_path: fifoPath },
+          { signal: controller.signal },
+        ),
+      );
+      expect(outcome.state).toBe("completed");
+      if (outcome.state !== "completed")
+        throw new Error("Aborted capture read waited for a FIFO writer");
+      if (outcome.result.ok) throw new Error("Expected cancellation");
+      expect(outcome.result.error._tag).toBe("AnalysisCancelledError");
+      await expect(access(input.output_directory)).rejects.toMatchObject({
+        code: "ENOENT",
+      });
+    },
+  );
+});
+
+describe("captured script path and permission failures", () => {
   it("reports a directory selected as the capture as invalid input", async () => {
     const { root, input } = await setup();
     const directory = join(root, "captures");
diff --git a/tests/boundary/mcp/webScriptSelectionMcp.test.ts b/tests/boundary/mcp/webScriptSelectionMcp.test.ts
new file mode 100644
index 000000000..062718fc0
--- /dev/null
+++ b/tests/boundary/mcp/webScriptSelectionMcp.test.ts
@@ -0,0 +1,78 @@
+import { execFile } from "node:child_process";
+import { access } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+
+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
+import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
+import { expect, it, onTestFinished } from "vitest";
+
+import { silentLogger } from "../../../src/logger.js";
+import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
+import { registerWebScriptTool } from "../../../src/server/registerWebScriptTool.js";
+import { ToolResultDelivery } from "../../../src/server/toolResult.js";
+import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
+import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+it.skipIf(process.platform === "win32")(
+  "returns a capture_path invalid_request for a named pipe without waiting or publishing output",
+  async () => {
+    const root = await createTestTempDirectory("rea-script-selection-mcp-");
+    const capturePath = join(root, "capture.pipe");
+    const outputDirectory = join(root, "export");
+    await promisify(execFile)("mkfifo", [capturePath]);
+
+    const server = new EvidenceMcpServer(
+      { name: "script-selection", version: "1" },
+      {},
+      undefined,
+      new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
+    );
+    registerWebScriptTool(server, {
+      logger: silentLogger,
+      recordEvidence: undefined,
+    });
+    const client = new Client({ name: "script-selection-test", version: "1" });
+    onTestFinished(async () => {
+      await client.close();
+      await server.close();
+    });
+    const [clientTransport, serverTransport] =
+      InMemoryTransport.createLinkedPair();
+    await server.connect(serverTransport);
+    await client.connect(clientTransport);
+
+    const outcome = await readWithoutFifoWriter(capturePath, () =>
+      client.callTool({
+        name: "export_web_scripts",
+        arguments: {
+          capture_path: capturePath,
+          output_directory: outputDirectory,
+        },
+      }),
+    );
+    expect(outcome.state).toBe("completed");
+    if (outcome.state !== "completed")
+      throw new Error("MCP capture selection waited for a FIFO writer");
+    expect(parseMcpToolError(outcome.result)).toMatchObject({
+      error: {
+        code: "invalid_request",
+        details: {
+          operation: "export_web_scripts",
+          issues: [
+            {
+              path: ["capture_path"],
+              reason: "invalid_value",
+              message: expect.stringContaining("regular file"),
+            },
+          ],
+        },
+      },
+    });
+    expect(JSON.stringify(outcome.result)).toContain(capturePath);
+    await expect(access(outputDirectory)).rejects.toMatchObject({
+      code: "ENOENT",
+    });
+  },
+);
diff --git a/tests/fixtures/fifoInput.ts b/tests/fixtures/fifoInput.ts
new file mode 100644
index 000000000..f5b81c17b
--- /dev/null
+++ b/tests/fixtures/fifoInput.ts
@@ -0,0 +1,36 @@
+import { constants } from "node:fs";
+import { open } from "node:fs/promises";
+
+type FifoReadOutcome =
+  | { state: "completed"; result: T }
+  | { state: "timed-out" };
+
+/** Bound a writer-free FIFO regression and release a blocking reader on failure. */
+export const readWithoutFifoWriter = async (
+  fifoPath: string,
+  read: () => Promise,
+): Promise> => {
+  const pending = read();
+  let timeout: NodeJS.Timeout | undefined;
+  try {
+    return await Promise.race([
+      pending.then((result): FifoReadOutcome => ({
+        state: "completed",
+        result,
+      })),
+      new Promise>((resolve) => {
+        timeout = setTimeout(() => resolve({ state: "timed-out" }), 1_000);
+      }),
+    ]);
+  } finally {
+    if (timeout !== undefined) clearTimeout(timeout);
+    // Release a blocking readFile open and await its EOF and cleanup.
+    // O_RDWR also completes when the fixed reader has already rejected.
+    const writer = await open(
+      fifoPath,
+      constants.O_RDWR | constants.O_NONBLOCK,
+    );
+    await writer.close();
+    await pending;
+  }
+};

From 3f59a84bd1039763bb349894542601ed78be2033 Mon Sep 17 00:00:00 2001
From: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:54:42 +0800
Subject: [PATCH 048/189] fix(contracts): advertise NUL with a portable hex
 escape

Use the equivalent hex NUL spelling in named public contracts while preserving current path and reserved-name validation. Verify converted JSON Schema and real stdio catalog consumers.

Closes #1329

Co-authored-by: Yi-111-a <97448247+Yi-111-a@users.noreply.github.com>
---
 src/contracts/native/nativeToolContracts.ts        |  2 +-
 src/domain/apple/dylibResolution.ts                |  2 +-
 src/domain/javascript/electronActiveObservation.ts |  2 +-
 src/domain/localPath.ts                            | 12 ++++++++++--
 src/domain/native/nativeCallObservation.ts         |  8 +++-----
 src/domain/process/processScenario.ts              |  6 +++---
 tests/boundary/mcp/advertisedPatternsVMode.test.ts | 13 ++++++++-----
 7 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/src/contracts/native/nativeToolContracts.ts b/src/contracts/native/nativeToolContracts.ts
index af1e1f016..093add61e 100644
--- a/src/contracts/native/nativeToolContracts.ts
+++ b/src/contracts/native/nativeToolContracts.ts
@@ -71,7 +71,7 @@ export const swiftSymbolsSchema = z
       .string()
       .min(1)
       .regex(/^[^\n]*$/u, "Each Swift symbol must be one line.")
-      .regex(/^[^\u0000]*$/u, "Swift symbols cannot contain NUL."),
+      .regex(/^[^\x00]*$/u, "Swift symbols cannot contain NUL."),
   )
   .min(1);
 
diff --git a/src/domain/apple/dylibResolution.ts b/src/domain/apple/dylibResolution.ts
index 466344d6a..86dc4902e 100644
--- a/src/domain/apple/dylibResolution.ts
+++ b/src/domain/apple/dylibResolution.ts
@@ -25,7 +25,7 @@ import {
  * patterns avoid look-around, which RE2 and Rust validators reject.
  */
 const ROOT_RELATIVE_PATH =
-  /^(?:[^\x2f\\\u0000.][^\x2f\\\u0000]*|\.[^\x2f\\\u0000.][^\x2f\\\u0000]*|\.\.[^\x2f\\\u0000]+)(?:\x2f(?:[^\x2f\\\u0000.][^\x2f\\\u0000]*|\.[^\x2f\\\u0000.][^\x2f\\\u0000]*|\.\.[^\x2f\\\u0000]+))*$/u;
+  /^(?:[^\x2f\\\x00.][^\x2f\\\x00]*|\.[^\x2f\\\x00.][^\x2f\\\x00]*|\.\.[^\x2f\\\x00]+)(?:\x2f(?:[^\x2f\\\x00.][^\x2f\\\x00]*|\.[^\x2f\\\x00.][^\x2f\\\x00]*|\.\.[^\x2f\\\x00]+))*$/u;
 const rootRelativePathSchema = z
   .string()
   .min(1)
diff --git a/src/domain/javascript/electronActiveObservation.ts b/src/domain/javascript/electronActiveObservation.ts
index 9f2e90b03..f46acfe6c 100644
--- a/src/domain/javascript/electronActiveObservation.ts
+++ b/src/domain/javascript/electronActiveObservation.ts
@@ -81,7 +81,7 @@ export const electronActiveObservationInputSchema = z.strictObject({
     .array(
       z
         .string()
-        .regex(/^[^\u0000]*$/u, "Electron arguments must not contain NUL"),
+        .regex(/^[^\x00]*$/u, "Electron arguments must not contain NUL"),
     )
     .default([]),
   actions: z.array(actionSchema).default([]),
diff --git a/src/domain/localPath.ts b/src/domain/localPath.ts
index 3226c2e44..d3d200189 100644
--- a/src/domain/localPath.ts
+++ b/src/domain/localPath.ts
@@ -1,11 +1,19 @@
 import { isAbsolute, relative, sep } from "node:path";
 import { z } from "zod";
 
-/** Preserve selected filesystem names while rejecting OS-invalid NUL bytes. */
+/**
+ * Preserve selected filesystem names while rejecting OS-invalid NUL bytes.
+ *
+ * The pattern spells NUL as `\x00` rather than `\u0000`. Both accept exactly the
+ * same strings. The hex form also avoids the short `\0` spelling rejected by
+ * strict schema consumers. A client can reject its entire tool request when
+ * one advertised pattern cannot compile. See `offsetDateTimeSchema` for the
+ * same hex-escape convention.
+ */
 export const localPathStringSchema = z
   .string()
   .min(1)
-  .regex(/^[^\u0000]*$/u, "Local filesystem paths cannot contain NUL");
+  .regex(/^[^\x00]*$/u, "Local filesystem paths cannot contain NUL");
 
 /** Test lexical containment on the host platform; callers must resolve symlinks first. */
 export const isPathWithinRoot = (root: string, path: string): boolean => {
diff --git a/src/domain/native/nativeCallObservation.ts b/src/domain/native/nativeCallObservation.ts
index c43a97195..68a56e569 100644
--- a/src/domain/native/nativeCallObservation.ts
+++ b/src/domain/native/nativeCallObservation.ts
@@ -5,7 +5,7 @@ const hexSchema = z.string().regex(/^0x[0-9a-f]+$/u);
 const nativeString = z
   .string()
   .regex(
-    /^[^\u0000]*$/u,
+    /^[^\x00]*$/u,
     "Native launch and breakpoint strings cannot contain NUL",
   );
 /** Objective-C class names and selectors never contain spaces or brackets. */
@@ -61,10 +61,8 @@ export const nativeCallObservationInputSchema = z.strictObject({
       z
         .string()
         .min(1)
-        .regex(/^[^=\u0000]+$/u, "Environment names cannot contain '=' or NUL"),
-      z
-        .string()
-        .regex(/^[^\u0000]*$/u, "Environment values cannot contain NUL"),
+        .regex(/^[^=\x00]+$/u, "Environment names cannot contain '=' or NUL"),
+      z.string().regex(/^[^\x00]*$/u, "Environment values cannot contain NUL"),
     )
     .default({})
     .describe("Overrides on top of the environment REA runs with."),
diff --git a/src/domain/process/processScenario.ts b/src/domain/process/processScenario.ts
index 8b980faa0..8312e1d2a 100644
--- a/src/domain/process/processScenario.ts
+++ b/src/domain/process/processScenario.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
 const positiveBudget = z.number().int().safe().positive();
 const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
 const reservedRunIdEnvironmentName = "REA_PROCESS_RUN_ID";
-const ENVIRONMENT_NAME_CHARACTER = "[^=\\u0000]";
+const ENVIRONMENT_NAME_CHARACTER = "[^=\\x00]";
 
 /**
  * Nonempty environment names other than the reserved run identifier. The
@@ -20,7 +20,7 @@ const environmentNamePattern = (reserved: string): RegExp => {
     const character = reserved[index] ?? "";
     // Diverge here, match the next reserved character, or (after a nonempty
     // prefix) end the name early.
-    const choice = `[^=\\u0000${character}]${ENVIRONMENT_NAME_CHARACTER}*|${character}${rest}`;
+    const choice = `[^=\\x00${character}]${ENVIRONMENT_NAME_CHARACTER}*|${character}${rest}`;
     rest = index === 0 ? choice : `(?:${choice})?`;
   }
   return new RegExp(`^(?:${rest})$`, "u");
@@ -38,7 +38,7 @@ const environmentName = z
 const childProcessString = z
   .string()
   .regex(
-    /^[^\u0000]*$/u,
+    /^[^\x00]*$/u,
     "Values passed to operating-system APIs cannot contain NUL",
   );
 export const normalizationSchema = z.object({
diff --git a/tests/boundary/mcp/advertisedPatternsVMode.test.ts b/tests/boundary/mcp/advertisedPatternsVMode.test.ts
index 024c42d12..b48fe27aa 100644
--- a/tests/boundary/mcp/advertisedPatternsVMode.test.ts
+++ b/tests/boundary/mcp/advertisedPatternsVMode.test.ts
@@ -79,9 +79,12 @@ it("advertises portable NUL escapes and patterns that compile in all JS modes",
   ).toEqual([]);
 
   // DeepSeek rejects the short NUL escape even though V8 accepts it in all
-  // three modes. Schema compilation must not hide that interchange failure.
-  expect(patterns.filter(({ pattern }) => pattern.includes("\\0"))).toEqual([]);
-  expect(patterns.some(({ pattern }) => pattern.includes("\\u0000"))).toBe(
-    true,
-  );
+  // three modes. Keep the shared hex spelling across the advertised catalog;
+  // actual provider acceptance is verified separately from JS compilation.
+  expect(
+    patterns.filter(
+      ({ pattern }) => pattern.includes("\\0") || pattern.includes("\\u0000"),
+    ),
+  ).toEqual([]);
+  expect(patterns.some(({ pattern }) => pattern.includes("\\x00"))).toBe(true);
 });

From b1e85ad711743a594c572dbd5b0d5cb664e2a502 Mon Sep 17 00:00:00 2001
From: keemsisi 
Date: Fri, 9 Oct 2026 19:07:30 +0100
Subject: [PATCH 049/189] perf(javascript): index version relationships once
 per comparison (#1347)

relationshipSignature rebuilt a node map and scanned every graph edge
for each side of each matched pair, so comparison cost grew as
pairs x (nodes + edges). Build node and adjacency indexes once per
graph in ItemContext; signatures, sorting and output are unchanged.
At 4000 matched modules, end-to-end compare: 5.7s -> 2.9s (2 edges
per node) and 10.4s -> 5.8s (6 edges per node); 8000: 3.3x and 2.5x.
Output JSON is byte-identical on the base commit.
---
 .../javascriptApplicationVersionItems.ts      |  84 ++++++---
 ...iptApplicationVersionRelationships.test.ts | 175 ++++++++++++++++++
 2 files changed, 232 insertions(+), 27 deletions(-)
 create mode 100644 src/domain/javascript/javascriptApplicationVersionRelationships.test.ts

diff --git a/src/domain/javascript/javascriptApplicationVersionItems.ts b/src/domain/javascript/javascriptApplicationVersionItems.ts
index 7e931904f..731d29b82 100644
--- a/src/domain/javascript/javascriptApplicationVersionItems.ts
+++ b/src/domain/javascript/javascriptApplicationVersionItems.ts
@@ -27,6 +27,19 @@ interface ItemContext {
   readonly rightNativeEvidence: readonly Evidence[];
   readonly pairByLeft: ReadonlyMap;
   readonly pairByRight: ReadonlyMap;
+  readonly leftRelationships: RelationshipIndex;
+  readonly rightRelationships: RelationshipIndex;
+}
+
+interface IndexedRelationship {
+  readonly direction: "in" | "out";
+  readonly relation: ApplicationEdge["relation"];
+  readonly neighborId: string;
+}
+
+interface RelationshipIndex {
+  readonly nodeById: ReadonlyMap;
+  readonly adjacency: ReadonlyMap;
 }
 
 type OneSidedNode =
@@ -53,7 +66,10 @@ type ComparisonItemSemantic<
 /** Classify matched, unmatched, and ambiguous nodes without inventing absence. */
 export const classifyJavaScriptApplicationVersions = (
   matching: ApplicationVersionMatchingProjection,
-  context: Omit,
+  context: Omit<
+    ItemContext,
+    "pairByLeft" | "pairByRight" | "leftRelationships" | "rightRelationships"
+  >,
 ): ApplicationVersionItemProjection => {
   const pairByLeft = new Map(
     matching.pairs.map(({ left, right }) => [
@@ -67,7 +83,13 @@ export const classifyJavaScriptApplicationVersions = (
       `pair:${left.node_id}:${right.node_id}`,
     ]),
   );
-  const fullContext: ItemContext = { ...context, pairByLeft, pairByRight };
+  const fullContext: ItemContext = {
+    ...context,
+    pairByLeft,
+    pairByRight,
+    leftRelationships: indexRelationships(context.leftGraph),
+    rightRelationships: indexRelationships(context.rightGraph),
+  };
   const leftItems = matching.unmatchedLeft.map((node) => {
     const candidates = matching.candidatesForLeft.get(node.node_id) ?? [];
     return unmatchedItem(
@@ -339,37 +361,45 @@ const properties = (node: ApplicationNode) =>
       compareUnicodeCodePoints(canonicalJson(left), canonicalJson(right)),
     );
 
+const indexRelationships = (
+  graph: JavaScriptApplicationGraph,
+): RelationshipIndex => {
+  const adjacency = new Map();
+  const add = (nodeId: string, relationship: IndexedRelationship): void => {
+    const existing = adjacency.get(nodeId);
+    if (existing === undefined) adjacency.set(nodeId, [relationship]);
+    else existing.push(relationship);
+  };
+  for (const edge of graph.edges) {
+    add(edge.source_node_id, {
+      direction: "out",
+      relation: edge.relation,
+      neighborId: edge.target_node_id,
+    });
+    if (edge.target_node_id !== edge.source_node_id)
+      add(edge.target_node_id, {
+        direction: "in",
+        relation: edge.relation,
+        neighborId: edge.source_node_id,
+      });
+  }
+  return {
+    nodeById: new Map(graph.nodes.map((value) => [value.node_id, value])),
+    adjacency,
+  };
+};
+
 const relationshipSignature = (
   node: ApplicationNode,
   side: "left" | "right",
   context: ItemContext,
 ): string => {
-  const graph = side === "left" ? context.leftGraph : context.rightGraph;
+  const { nodeById, adjacency } =
+    side === "left" ? context.leftRelationships : context.rightRelationships;
   const paired = side === "left" ? context.pairByLeft : context.pairByRight;
-  const nodeById = new Map(graph.nodes.map((value) => [value.node_id, value]));
-  const signatures = graph.edges.flatMap((edge) => {
-    if (edge.source_node_id === node.node_id)
-      return [
-        edgeSignature({
-          direction: "out",
-          relation: edge.relation,
-          neighborId: edge.target_node_id,
-          paired,
-          nodeById,
-        }),
-      ];
-    if (edge.target_node_id === node.node_id)
-      return [
-        edgeSignature({
-          direction: "in",
-          relation: edge.relation,
-          neighborId: edge.source_node_id,
-          paired,
-          nodeById,
-        }),
-      ];
-    return [];
-  });
+  const signatures = (adjacency.get(node.node_id) ?? []).map((relationship) =>
+    edgeSignature({ ...relationship, paired, nodeById }),
+  );
   return canonicalJson(signatures.sort(compareUnicodeCodePoints));
 };
 
diff --git a/src/domain/javascript/javascriptApplicationVersionRelationships.test.ts b/src/domain/javascript/javascriptApplicationVersionRelationships.test.ts
new file mode 100644
index 000000000..40b0dc078
--- /dev/null
+++ b/src/domain/javascript/javascriptApplicationVersionRelationships.test.ts
@@ -0,0 +1,175 @@
+import { describe, expect, it } from "vitest";
+
+import {
+  createJavaScriptApplicationEdge,
+  createJavaScriptApplicationGraph,
+  createJavaScriptApplicationNode,
+  type JavaScriptApplicationGraph,
+} from "./javascriptApplicationGraph.js";
+import {
+  artifactEvidence,
+  completeCoverage,
+} from "./javascriptApplicationGraph.fixture.js";
+import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js";
+
+const LEFT_SHA = "a".repeat(64);
+const RIGHT_SHA = "b".repeat(64);
+const NAMES = ["a", "b", "c", "d"] as const;
+type ModuleName = (typeof NAMES)[number];
+type Relation = "imports" | "contains";
+type EdgeSpec = readonly [ModuleName, ModuleName, Relation];
+
+const sourceDigest = (name: string): string =>
+  name.charCodeAt(0).toString(16).padStart(64, "0");
+
+const buildGraph = (
+  artifactSha: string,
+  edges: readonly EdgeSpec[],
+  order: "forward" | "reverse" = "forward",
+): JavaScriptApplicationGraph => {
+  const names = order === "forward" ? [...NAMES] : [...NAMES].reverse();
+  const nodes = names.map((name) =>
+    createJavaScriptApplicationNode({
+      kind: "javascript-module",
+      identity: {
+        strategy: "canonical-path",
+        stability: "artifact-version",
+        artifact_sha256: artifactSha,
+        path: `${name}.js`,
+      },
+      observations: [
+        {
+          label: `${name}.js`,
+          properties: { source_sha256: sourceDigest(name) },
+          evidence: artifactEvidence(artifactSha, `${name}.js`),
+        },
+      ],
+    }),
+  );
+  const idOf = (name: ModuleName): string => {
+    const node = nodes.find(({ identity }) =>
+      identity.strategy === "canonical-path"
+        ? identity.path === `${name}.js`
+        : false,
+    );
+    if (node === undefined) throw new Error(`Missing fixture node ${name}`);
+    return node.node_id;
+  };
+  const ordered = order === "forward" ? [...edges] : [...edges].reverse();
+  return createJavaScriptApplicationGraph({
+    schema: "JavaScriptApplicationGraph",
+    root_node_ids: [idOf("a")],
+    nodes,
+    edges: ordered.map(([source, target, relation]) =>
+      createJavaScriptApplicationEdge({
+        source_node_id: idOf(source),
+        target_node_id: idOf(target),
+        relation,
+        properties: {},
+        evidence: artifactEvidence(artifactSha, `${source}.js`),
+      }),
+    ),
+    coverage: completeCoverage,
+    limitations: [],
+  });
+};
+
+const relationshipChanges = (
+  left: JavaScriptApplicationGraph,
+  right: JavaScriptApplicationGraph,
+): string[] => {
+  const result = compareJavaScriptApplicationVersions({
+    left: {
+      evidenceId: `ev_${"1".repeat(64)}`,
+      rootArtifactSha256: LEFT_SHA,
+      graph: left,
+    },
+    right: {
+      evidenceId: `ev_${"2".repeat(64)}`,
+      rootArtifactSha256: RIGHT_SHA,
+      graph: right,
+    },
+    leftNativeEvidence: [],
+    rightNativeEvidence: [],
+  });
+  expect(result.summary.added + result.summary.removed).toBe(0);
+  return result.items
+    .filter(({ dimensions }) => dimensions.includes("relationships"))
+    .map(({ left_node_id: id }) => {
+      const node = left.nodes.find(({ node_id: nodeId }) => nodeId === id);
+      const label = node?.observations[0]?.label;
+      if (label === undefined || label === null)
+        throw new Error("Changed item has no node");
+      return label;
+    })
+    .sort();
+};
+
+const BASE_EDGES: readonly EdgeSpec[] = [
+  ["a", "b", "imports"],
+  ["b", "c", "imports"],
+  ["a", "c", "contains"],
+  ["c", "b", "imports"],
+];
+
+describe("application version relationship comparison", () => {
+  it("reports no relationship change for identical topology in any node or edge order", () => {
+    expect(
+      relationshipChanges(
+        buildGraph(LEFT_SHA, BASE_EDGES),
+        buildGraph(RIGHT_SHA, BASE_EDGES, "reverse"),
+      ),
+    ).toEqual([]);
+  });
+
+  it("flags both endpoints when an edge relation changes", () => {
+    const changed: readonly EdgeSpec[] = [
+      ["a", "b", "imports"],
+      ["b", "c", "contains"],
+      ["a", "c", "contains"],
+      ["c", "b", "imports"],
+    ];
+    expect(
+      relationshipChanges(
+        buildGraph(LEFT_SHA, BASE_EDGES),
+        buildGraph(RIGHT_SHA, changed),
+      ),
+    ).toEqual(["b.js", "c.js"]);
+  });
+
+  it("flags a node whose only change is an incoming edge", () => {
+    const left: readonly EdgeSpec[] = [["a", "b", "imports"]];
+    const right: readonly EdgeSpec[] = [
+      ["a", "b", "imports"],
+      ["c", "b", "imports"],
+    ];
+    expect(
+      relationshipChanges(
+        buildGraph(LEFT_SHA, left),
+        buildGraph(RIGHT_SHA, right),
+      ),
+    ).toEqual(["b.js", "c.js"]);
+  });
+
+  it("flags a node when an edge is re-pointed at a different matched neighbour", () => {
+    const left: readonly EdgeSpec[] = [["a", "b", "imports"]];
+    const right: readonly EdgeSpec[] = [["a", "c", "imports"]];
+    expect(
+      relationshipChanges(
+        buildGraph(LEFT_SHA, left),
+        buildGraph(RIGHT_SHA, right),
+      ),
+    ).toEqual(["a.js", "b.js", "c.js"]);
+  });
+
+  it("distinguishes edge direction between the same pair", () => {
+    const left: readonly EdgeSpec[] = [["a", "b", "imports"]];
+    const right: readonly EdgeSpec[] = [["b", "a", "imports"]];
+    expect(
+      relationshipChanges(
+        buildGraph(LEFT_SHA, left),
+        buildGraph(RIGHT_SHA, right),
+      ),
+    ).toEqual(["a.js", "b.js"]);
+  });
+});

From 1c123493a21cc579ba7532c40e7ef30df45db3e8 Mon Sep 17 00:00:00 2001
From: You Wish <29498139+Y0UW1SH@users.noreply.github.com>
Date: Fri, 9 Oct 2026 14:12:33 -0400
Subject: [PATCH 050/189] fix(hopper): allow restart after verified
 owned-provider shutdown

Co-authored-by: YouWish <29498139+Y0UW1SH@users.noreply.github.com>
---
 .github/workflows/ci.yml                      |   1 +
 docs/installation.md                          |  11 +
 src/hopper/HopperCleanup.ts                   |   2 +-
 .../providers/ghidra/ghidraLauncher.test.ts   |  56 +--
 .../hopper/hopperClient.cleanup.test.ts       | 103 ++---
 .../hopper/hopperClient.cleanupRetry.test.ts  | 437 ++++++++++++++++++
 6 files changed, 513 insertions(+), 97 deletions(-)
 create mode 100644 tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 78530bca3..ea474dbf0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -463,6 +463,7 @@ jobs:
           tests/boundary/providers/ghidra/ghidraTransport.test.ts
           tests/boundary/providers/ghidra/ghidraTargetSnapshot.test.ts
           tests/boundary/providers/ghidra/ghidraLauncher.test.ts
+          tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts
           src/windows/WindowsNativeLoader.test.ts
           src/windows/WindowsOwnedProcess.test.ts
           src/ghidra/GhidraLauncherEnvironment.test.ts
diff --git a/docs/installation.md b/docs/installation.md
index 2b9c78e0d..89fcbba45 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -416,6 +416,17 @@ Closing or switching a target closes its bound Hopper document, shuts down REA's
 bridge and removes its temporary socket directory while preserving the Hopper
 application and unrelated documents. A `cleanup_incomplete`
 result identifies resources whose cleanup could not be verified.
+REA retains unresolved cleanup ownership and any confirmed shutdown phases.
+After addressing the reported failure, retry `close_binary` on the same
+connection. Unconfirmed document or process cleanup retains the target/application
+lease and prevents another client from launching against that owned resource.
+Once document and process closure are confirmed, the lease can be released even
+if temporary-file cleanup fails. Another client can then launch, but the owning
+client must finish its retained cleanup before starting again.
+An unconfirmed external document can be retried while its authenticated bridge
+remains connected. If that bridge has disconnected, another close cannot confirm
+the document: inspect and close the reported document in Hopper before ending
+the owning REA connection.
 
 ### Hopper in CI
 
diff --git a/src/hopper/HopperCleanup.ts b/src/hopper/HopperCleanup.ts
index d3c79dc26..346e0b894 100644
--- a/src/hopper/HopperCleanup.ts
+++ b/src/hopper/HopperCleanup.ts
@@ -269,7 +269,7 @@ const stopProcess = async (
   input.logger.info(diagnostic, "Owned Hopper launcher shutdown completed");
   if (stopped.status !== "incomplete") {
     if (
-      input.resources.launch?.shutdownMode === "process-cleanup" &&
+      input.resources.launch?.providerLifetime === "launcher-process" &&
       stopped.status !== "not-owned"
     )
       input.resources.shutdownConfirmed = true;
diff --git a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts
index 87850070d..28d9800f4 100644
--- a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts
+++ b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts
@@ -235,33 +235,35 @@ describe("Ghidra headless launcher", () => {
         profileDigest: "a".repeat(64),
       });
       if (!launched.ok) throw launched.error;
-      const capturePath = join(runtimeRoot, "launch-capture.json");
-      await vi.waitFor(() => access(`${capturePath}.ready`), {
-        timeout: 10_000,
-      });
-      const capture = launchCaptureSchema.parse(
-        JSON.parse(await readFile(capturePath, "utf8")),
-      );
-      const encodedArguments = JSON.stringify(capture.arguments);
-      const encodedEnvironment = JSON.stringify(capture.environment);
-      expect(encodedArguments).not.toContain(token);
-      expect(encodedEnvironment).not.toContain(token);
-      expect(capture).toMatchObject({
-        ...(process.platform === "win32" ? {} : { descriptor_mode: 0o600 }),
-        descriptor_has_token: true,
-      });
-      expectIsolatedEnvironment(capture.environment, runtimeRoot, javaHome);
-      expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).toBe("");
-      if (process.platform !== "win32")
-        expect(
-          (await stat(join(runtimeRoot, "ownership.json"))).mode & 0o777,
-        ).toBe(0o600);
-
-      const cleaned = await launched.value.cleanup?.();
-      expect(cleaned).toMatchObject({ cleaned: true });
-      await expect(
-        access(join(runtimeRoot, "project")),
-      ).resolves.toBeUndefined();
+      try {
+        const capturePath = join(runtimeRoot, "launch-capture.json");
+        await vi.waitFor(() => access(`${capturePath}.ready`), {
+          timeout: 10_000,
+        });
+        const capture = launchCaptureSchema.parse(
+          JSON.parse(await readFile(capturePath, "utf8")),
+        );
+        const encodedArguments = JSON.stringify(capture.arguments);
+        const encodedEnvironment = JSON.stringify(capture.environment);
+        expect(encodedArguments).not.toContain(token);
+        expect(encodedEnvironment).not.toContain(token);
+        expect(capture).toMatchObject({
+          ...(process.platform === "win32" ? {} : { descriptor_mode: 0o600 }),
+          descriptor_has_token: true,
+        });
+        expectIsolatedEnvironment(capture.environment, runtimeRoot, javaHome);
+        expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).toBe("");
+        if (process.platform !== "win32")
+          expect(
+            (await stat(join(runtimeRoot, "ownership.json"))).mode & 0o777,
+          ).toBe(0o600);
+      } finally {
+        const cleaned = await launched.value.cleanup?.();
+        expect(cleaned).toMatchObject({ cleaned: true });
+        await expect(
+          access(join(runtimeRoot, "project")),
+        ).resolves.toBeUndefined();
+      }
     },
   );
 });
diff --git a/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts b/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts
index f595db837..6c8c88a3b 100644
--- a/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts
+++ b/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts
@@ -54,29 +54,8 @@ class OwnedFixtureLauncher implements BridgeLauncher {
 }
 
 class UnconfirmedFixtureLauncher implements BridgeLauncher {
-  launch(session: BridgeSession) {
-    return Promise.resolve(
-      ok({
-        process: spawn(
-          process.execPath,
-          [
-            fixturePath,
-            session.socketPath,
-            session.token,
-            session.runId,
-            "unconfirmed",
-          ],
-          { stdio: ["ignore", "ignore", "pipe"] },
-        ),
-        ownsProcessLifetime: false,
-        providerLifetime: "external-application" as const,
-        shutdownMode: "bridge-request" as const,
-      }),
-    );
-  }
-}
+  constructor(readonly ownsProcessLifetime = false) {}
 
-class UnconfirmedOwnedFixtureLauncher implements BridgeLauncher {
   launch(session: BridgeSession) {
     return Promise.resolve(
       ok({
@@ -91,8 +70,8 @@ class UnconfirmedOwnedFixtureLauncher implements BridgeLauncher {
           ],
           { stdio: ["ignore", "ignore", "pipe"] },
         ),
-        ownsProcessLifetime: true as const,
-        providerLifetime: "launcher-process" as const,
+        ownsProcessLifetime: this.ownsProcessLifetime,
+        providerLifetime: "external-application" as const,
         shutdownMode: "bridge-request" as const,
       }),
     );
@@ -158,55 +137,41 @@ describe("HopperClient cleanup", () => {
     });
   });
 
-  it("reports unconfirmed unowned document cleanup as a typed close failure", async () => {
-    const client = new HopperClient({
-      launcher: new UnconfirmedFixtureLauncher(),
-      startupTimeoutMs: 1_000,
-    });
-    clients.push(client);
-    expect((await client.start()).ok).toBe(true);
+  it.each([
+    ["unowned", false],
+    ["owned helper", true],
+  ] as const)(
+    "reports unconfirmed external document cleanup for an %s process",
+    async (_description, ownsProcessLifetime) => {
+      const client = new HopperClient({
+        launcher: new UnconfirmedFixtureLauncher(ownsProcessLifetime),
+        startupTimeoutMs: 1_000,
+      });
+      clients.push(client);
+      expect((await client.start()).ok).toBe(true);
 
-    const closed = await client.close();
+      const closed = await client.close();
 
-    expect(closed).toMatchObject({
-      ok: false,
-      error: {
-        _tag: "ProviderAdapterError",
-        cleanupIncomplete: true,
-        cleanupResources: expect.arrayContaining(["hopper-document"]),
-      },
-    });
-    if (!closed.ok)
-      expect(projectAnalysisError(closed.error)).toMatchObject({
-        code: "cleanup_incomplete",
-        details: {
-          provider_id: "hopper",
-          operation: "close_binary",
-          cleanup: "incomplete",
-          resources: expect.arrayContaining(["hopper-document"]),
+      expect(closed).toMatchObject({
+        ok: false,
+        error: {
+          _tag: "ProviderAdapterError",
+          cleanupIncomplete: true,
+          cleanupResources: expect.arrayContaining(["hopper-document"]),
         },
       });
-  });
-
-  it("does not treat an owned launcher exit as bridge document shutdown", async () => {
-    const client = new HopperClient({
-      launcher: new UnconfirmedOwnedFixtureLauncher(),
-      startupTimeoutMs: 1_000,
-    });
-    clients.push(client);
-    expect((await client.start()).ok).toBe(true);
-
-    const closed = await client.close();
-
-    expect(closed).toMatchObject({
-      ok: false,
-      error: {
-        _tag: "ProviderAdapterError",
-        cleanupIncomplete: true,
-        cleanupResources: expect.arrayContaining(["hopper-document"]),
-      },
-    });
-  });
+      if (!closed.ok)
+        expect(projectAnalysisError(closed.error)).toMatchObject({
+          code: "cleanup_incomplete",
+          details: {
+            provider_id: "hopper",
+            operation: "close_binary",
+            cleanup: "incomplete",
+            resources: expect.arrayContaining(["hopper-document"]),
+          },
+        });
+    },
+  );
 
   it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
     const unrelated = spawn(
diff --git a/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts
new file mode 100644
index 000000000..3db6772e3
--- /dev/null
+++ b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts
@@ -0,0 +1,437 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { access, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { Socket } from "node:net";
+
+import { expect, it, onTestFinished } from "vitest";
+
+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
+import { HopperStartError } from "../../../../src/domain/hopperErrors.js";
+import { err, ok } from "../../../../src/domain/result.js";
+import type {
+  BridgeLaunch,
+  BridgeLauncher,
+  BridgeSession,
+} from "../../../../src/hopper/BridgeLauncher.js";
+import {
+  HopperClient,
+  type HopperClientOptions,
+} from "../../../../src/hopper/HopperClient.js";
+import {
+  type HopperOwnedResources,
+  cleanupHopperSession,
+} from "../../../../src/hopper/HopperCleanup.js";
+import { silentLogger } from "../../../../src/logger.js";
+import { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
+import { ProviderProcessSupervisor } from "../../../../src/process/ProviderProcess.js";
+
+class RetryCleanupLauncher implements BridgeLauncher {
+  readonly sessions: BridgeSession[] = [];
+  readonly processes: ChildProcess[] = [];
+  allowCleanup = false;
+
+  constructor(readonly externalDocument = false) {
+    onTestFinished(async () => {
+      for (const process of this.processes) await stopFixture(process);
+      for (const session of this.sessions)
+        await rm(session.directory, { recursive: true, force: true });
+    });
+  }
+
+  async launch(session: BridgeSession) {
+    this.sessions.push(session);
+    const preparedImagePath = join(session.directory, "image.macho");
+    await writeFile(preparedImagePath, "owned prepared backing image");
+    const child = spawn(
+      process.execPath,
+      ["-e", "setInterval(() => undefined, 1000)"],
+      { stdio: "ignore" },
+    );
+    this.processes.push(child);
+    const launch: BridgeLaunch = this.externalDocument
+      ? {
+          process: child,
+          ownsProcessLifetime: false,
+          providerLifetime: "external-application",
+          shutdownMode: "bridge-request",
+          preparedImagePath,
+        }
+      : {
+          process: child,
+          ownsProcessLifetime: true,
+          providerLifetime: "launcher-process",
+          shutdownMode: "process-cleanup",
+          preparedImagePath,
+          cleanup: async () => {
+            if (!this.allowCleanup)
+              return {
+                cleaned: false,
+                reason: "fixture transient cleanup denial",
+              };
+            await stopFixture(child);
+            return { cleaned: true, signaled: true };
+          },
+        };
+    return ok(launch);
+  }
+}
+
+const stopFixture = async (child: ChildProcess): Promise => {
+  if (child.exitCode !== null || child.signalCode !== null) return;
+  const exited = new Promise((resolve) =>
+    child.once("exit", () => resolve()),
+  );
+  child.kill("SIGKILL");
+  await exited;
+};
+
+const expectStoppedFixture = (
+  child: Pick,
+): void => {
+  expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
+  if (process.platform !== "win32") expect(child.signalCode).toBe("SIGKILL");
+};
+
+const createClient = (options: HopperClientOptions) => {
+  const client = new HopperClient({ startupTimeoutMs: 100, ...options });
+  onTestFinished(async () => {
+    await client.close();
+  });
+  return client;
+};
+
+const failedStartup = async (launcher: RetryCleanupLauncher) => {
+  const client = createClient({ launcher });
+  await expect(client.start()).resolves.toMatchObject({
+    ok: false,
+    error: {
+      _tag: "ProviderAdapterError",
+      cleanupIncomplete: true,
+      cause: { _tag: "HopperTimeoutError" },
+    },
+  });
+  const session = launcher.sessions[0];
+  const child = launcher.processes[0];
+  if (session === undefined || child === undefined)
+    throw new Error("Fixture launch was not observed");
+  return { client, session, child };
+};
+
+it("retains failed startup cleanup until an owned process and its backing image are closed", async () => {
+  const launcher = new RetryCleanupLauncher();
+  const { client, session, child } = await failedStartup(launcher);
+  const closed = await client.close();
+  expect(closed).toMatchObject({
+    ok: false,
+    error: {
+      cleanupIncomplete: true,
+      cleanupResources: [
+        "hopper-process",
+        "hopper-document",
+        session.directory,
+      ],
+    },
+  });
+  if (closed.ok) throw new Error("Expected incomplete fixture cleanup");
+  expect(projectAnalysisError(closed.error)).toMatchObject({
+    code: "cleanup_incomplete",
+    details: {
+      resources: ["hopper-process", "hopper-document", session.directory],
+    },
+  });
+  expect(child.exitCode).toBeNull();
+  expect(child.signalCode).toBeNull();
+  await expect(
+    readFile(join(session.directory, "image.macho"), "utf8"),
+  ).resolves.toBe("owned prepared backing image");
+
+  launcher.allowCleanup = true;
+  const first = client.close();
+  const second = client.close();
+  await expect(first).resolves.toEqual({ ok: true, value: null });
+  await expect(second).resolves.toEqual({ ok: true, value: null });
+  expectStoppedFixture(child);
+  await expect(access(session.directory)).rejects.toMatchObject({
+    code: "ENOENT",
+  });
+  await expect(client.close()).resolves.toEqual({
+    ok: true,
+    value: null,
+  });
+});
+
+it("keeps an unconfirmed external document visible across sequential closes", async () => {
+  const launcher = new RetryCleanupLauncher(true);
+  const runtimeRoot = await PrivateRuntimeRoot.create();
+  onTestFinished(() => runtimeRoot.close());
+  const launched = await launcher.launch({
+    directory: runtimeRoot.path,
+    socketPath: join(runtimeRoot.path, "bridge.sock"),
+    token: "fixture-token",
+    runId: "fixture-run",
+  });
+  if (!launched.ok) throw launched.error;
+  const child = launched.value.process;
+  const supervisor = new ProviderProcessSupervisor(launched.value);
+  onTestFinished(() => supervisor.dispose());
+  const resources: HopperOwnedResources = {
+    launch: launched.value,
+    processSupervisor: supervisor,
+    runtimeRoot,
+    shutdownConfirmed: false,
+  };
+  for (let attempt = 0; attempt < 2; attempt += 1) {
+    await expect(
+      cleanupHopperSession({
+        socket: undefined,
+        resources,
+        activeRequest: null,
+        retainDocument: false,
+        progress: undefined,
+        logger: silentLogger,
+        onDiagnostic: undefined,
+        request: () => Promise.resolve(ok(null)),
+        releaseTransport: (socket) => socket?.destroy(),
+      }),
+    ).resolves.toMatchObject({
+      ok: false,
+      error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
+    });
+  }
+  expect(child.exitCode).toBeNull();
+  expect(child.signalCode).toBeNull();
+  await expect(
+    access(join(runtimeRoot.path, "image.macho")),
+  ).resolves.toBeUndefined();
+});
+
+it("blocks a fresh launch while cleanup remains unverified", async () => {
+  const launcher = new RetryCleanupLauncher();
+  const { client, child } = await failedStartup(launcher);
+  await expect(client.start()).resolves.toMatchObject({
+    ok: false,
+    error: { _tag: "HopperProtocolError" },
+  });
+  expect(launcher.processes).toEqual([child]);
+  launcher.allowCleanup = true;
+  await expect(client.close()).resolves.toEqual({
+    ok: true,
+    value: null,
+  });
+});
+
+it("permits a fresh launch after stopping an owned bridge-request provider without an acknowledgement", async () => {
+  const fixture = new RetryCleanupLauncher();
+  fixture.allowCleanup = true;
+  const launcher: BridgeLauncher = {
+    async launch(session) {
+      const launched = await fixture.launch(session);
+      if (!launched.ok) return launched;
+      return ok({ ...launched.value, shutdownMode: "bridge-request" as const });
+    },
+  };
+  const client = createClient({ launcher });
+
+  for (let attempt = 0; attempt < 2; attempt += 1) {
+    await expect(client.start()).resolves.toMatchObject({
+      ok: false,
+      error: { _tag: "HopperTimeoutError" },
+    });
+    await expect(client.close()).resolves.toEqual({
+      ok: true,
+      value: null,
+    });
+  }
+  expect(fixture.sessions).toHaveLength(2);
+  for (const session of fixture.sessions)
+    await expect(access(session.directory)).rejects.toMatchObject({
+      code: "ENOENT",
+    });
+  for (const child of fixture.processes) expectStoppedFixture(child);
+});
+
+it("retains a cross-client lease until owned cleanup succeeds", async () => {
+  const fixture = new RetryCleanupLauncher();
+  let owner: string | undefined;
+  const launcher: BridgeLauncher = {
+    async launch(session) {
+      if (owner !== undefined)
+        return err(new HopperStartError({ ownerRunId: owner }));
+      const launched = await fixture.launch(session);
+      if (!launched.ok) return launched;
+      owner = session.runId;
+      return ok({
+        ...launched.value,
+        releaseLease: async () => void (owner = undefined),
+      });
+    },
+  };
+  const first = createClient({ launcher, runId: "first" });
+  const second = createClient({ launcher, runId: "second" });
+  await expect(first.start()).resolves.toMatchObject({ ok: false });
+  await expect(second.start()).resolves.toMatchObject({
+    ok: false,
+    error: { _tag: "HopperStartError", ownerRunId: "first" },
+  });
+  expect(fixture.processes).toHaveLength(1);
+
+  fixture.allowCleanup = true;
+  await expect(first.close()).resolves.toEqual({ ok: true, value: null });
+  await expect(second.start()).resolves.toMatchObject({
+    ok: false,
+    error: { _tag: "HopperTimeoutError" },
+  });
+  expect(fixture.processes).toHaveLength(2);
+  expect(owner).toBeUndefined();
+});
+
+it("retries a failed lease release after document, process, and runtime cleanup are confirmed", async () => {
+  const fixture = new RetryCleanupLauncher();
+  fixture.allowCleanup = true;
+  let releaseAllowed = false;
+  const launcher: BridgeLauncher = {
+    async launch(session) {
+      const launched = await fixture.launch(session);
+      if (!launched.ok) return launched;
+      return ok({
+        ...launched.value,
+        releaseLease: async () => {
+          if (!releaseAllowed) throw new Error("fixture lease release denial");
+        },
+      });
+    },
+  };
+  const client = createClient({ launcher });
+  await expect(client.start()).resolves.toMatchObject({ ok: false });
+  await expect(client.close()).resolves.toMatchObject({
+    ok: false,
+    error: { cleanupResources: ["hopper-lease"] },
+  });
+  await expect(client.start()).resolves.toMatchObject({
+    ok: false,
+    error: { _tag: "HopperProtocolError" },
+  });
+  releaseAllowed = true;
+  await expect(client.close()).resolves.toEqual({ ok: true, value: null });
+  expect(fixture.processes).toHaveLength(1);
+});
+
+it("preserves confirmed document shutdown while retrying owned process cleanup", async () => {
+  const launcher = new RetryCleanupLauncher();
+  const runtimeRoot = await PrivateRuntimeRoot.create();
+  onTestFinished(() => runtimeRoot.close());
+  const launched = await launcher.launch({
+    directory: runtimeRoot.path,
+    socketPath: join(runtimeRoot.path, "bridge.sock"),
+    token: "fixture-token",
+    runId: "fixture-run",
+  });
+  if (!launched.ok) throw launched.error;
+  const supervisor = new ProviderProcessSupervisor(launched.value);
+  onTestFinished(() => supervisor.dispose());
+  const input = {
+    resources: {
+      launch: launched.value,
+      processSupervisor: supervisor,
+      runtimeRoot,
+      shutdownConfirmed: false,
+    } satisfies HopperOwnedResources,
+    activeRequest: null,
+    retainDocument: false,
+    progress: undefined,
+    logger: silentLogger,
+    onDiagnostic: undefined,
+    request: () =>
+      Promise.resolve(
+        ok({
+          shutdown: true,
+          analysis_stopped: true,
+          document_closed: true,
+        }),
+      ),
+    releaseTransport: (socket: Socket | undefined) => socket?.destroy(),
+  };
+  const first = await cleanupHopperSession({ ...input, socket: new Socket() });
+  expect(first).toMatchObject({
+    ok: false,
+    error: { cleanupResources: ["hopper-process", runtimeRoot.path] },
+  });
+  launcher.allowCleanup = true;
+  const second = await cleanupHopperSession({
+    ...input,
+    socket: undefined,
+  });
+  expect(second).toEqual({ ok: true, value: null });
+  expectStoppedFixture(launched.value.process);
+  await expect(access(runtimeRoot.path)).rejects.toMatchObject({
+    code: "ENOENT",
+  });
+});
+
+it.each([
+  ["launcher-process", "waiting"],
+  ["launcher-process", "cancelled"],
+  ["external-application", "waiting"],
+  ["external-application", "cancelled"],
+] as const)(
+  "checks document closure for a %s provider with a %s request",
+  async (providerLifetime, callerState) => {
+    const launcher = new RetryCleanupLauncher();
+    launcher.allowCleanup = true;
+    const runtimeRoot = await PrivateRuntimeRoot.create();
+    onTestFinished(() => runtimeRoot.close());
+    const launched = await launcher.launch({
+      directory: runtimeRoot.path,
+      socketPath: join(runtimeRoot.path, "bridge.sock"),
+      token: "fixture-token",
+      runId: "fixture-run",
+    });
+    if (!launched.ok) throw launched.error;
+    const launch: BridgeLaunch = {
+      ...launched.value,
+      providerLifetime,
+      shutdownMode: "bridge-request",
+    };
+    const supervisor = new ProviderProcessSupervisor(launch);
+    onTestFinished(() => supervisor.dispose());
+    const resources: HopperOwnedResources = {
+      launch,
+      processSupervisor: supervisor,
+      runtimeRoot,
+      shutdownConfirmed: false,
+    };
+    const result = await cleanupHopperSession({
+      socket: new Socket(),
+      resources,
+      activeRequest: {
+        requestId: 1,
+        operation: "partial_then_wait",
+        elapsedMs: 0,
+        callerState,
+        queuedRequests: 0,
+      },
+      retainDocument: false,
+      progress: undefined,
+      logger: silentLogger,
+      onDiagnostic: undefined,
+      request: () =>
+        Promise.reject(new Error("Active request prevents shutdown")),
+      releaseTransport: (socket) => socket?.destroy(),
+    });
+    if (providerLifetime === "launcher-process") {
+      expect(result).toEqual({ ok: true, value: null });
+      await expect(access(runtimeRoot.path)).rejects.toMatchObject({
+        code: "ENOENT",
+      });
+    } else {
+      expect(result).toMatchObject({
+        ok: false,
+        error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
+      });
+      await expect(
+        access(join(runtimeRoot.path, "image.macho")),
+      ).resolves.toBeUndefined();
+    }
+    expectStoppedFixture(launch.process);
+  },
+);

From d5cb8aee063065a48233458e04771635167825c8 Mon Sep 17 00:00:00 2001
From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:22:03 +0800
Subject: [PATCH 051/189] fix(ci): scope verification and reuse native runners
 (#1344)

* fix(ci): scope documentation checks and cancel superseded runs

* ci: reuse package runners for native Inspector checks

* test(ci): share deterministic workflow Git fixtures
---
 .github/workflows/ci.yml                      |  65 ++----
 .../boundary/filesystem/ciChangeScope.test.ts | 203 ++++++++++++++++++
 .../filesystem/releaseCheckpoint.test.ts      |  33 +--
 tests/support/workflowGit.ts                  |  33 +++
 4 files changed, 259 insertions(+), 75 deletions(-)
 create mode 100644 tests/boundary/filesystem/ciChangeScope.test.ts
 create mode 100644 tests/support/workflowGit.ts

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ea474dbf0..97025afe7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -8,7 +8,9 @@ on:
 
 concurrency:
   group: ci-${{ github.event.pull_request.number || github.ref }}
-  cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+  # The latest main push verifies the full tree, including earlier changes.
+  # Publication uses its own release workflow and concurrency group.
+  cancel-in-progress: true
 
 env:
   HUSKY: "0"
@@ -47,15 +49,22 @@ jobs:
           BASE_SHA: ${{ github.event.pull_request.base.sha }}
           HEAD_SHA: ${{ github.event.pull_request.head.sha }}
         run: |
-          if [[ "${{ github.event_name }}" != "pull_request" ]]; then
+          if [[ "${GITHUB_EVENT_NAME}" != "pull_request" ]]; then
             echo "required=true" >> "${GITHUB_OUTPUT}"
-          elif git diff --quiet "${BASE_SHA}" "${HEAD_SHA}" -- \
+          # Compare the PR's changes, excluding unrelated updates on its base.
+          elif git diff --quiet "${BASE_SHA}...${HEAD_SHA}" -- \
             . \
             ':(exclude)docs/**' \
+            ':(top,exclude,glob)README*.md' \
             ':(exclude)AGENTS.md' \
             ':(exclude)CONTRIBUTING.md'; then
             echo "required=false" >> "${GITHUB_OUTPUT}"
           else
+            diff_status=$?
+            # A failed comparison must fail classification, not report a scope.
+            if [[ "${diff_status}" -ne 1 ]]; then
+              exit "${diff_status}"
+            fi
             echo "required=true" >> "${GITHUB_OUTPUT}"
           fi
 
@@ -302,7 +311,7 @@ jobs:
       - run: npm run verify:windows-native:artifact
       - run: npm run verify:package
       - name: Verify real Node Inspector discovery and observation
-        if: matrix.platform == 'darwin'
+        timeout-minutes: 10
         run: npm run verify:inspector
 
   apple-artifacts:
@@ -365,48 +374,6 @@ jobs:
           if-no-files-found: error
           retention-days: 30
 
-  javascript-runtime-observation:
-    name: JavaScript runtime observation (${{ matrix.os }})
-    needs: changes
-    if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
-    strategy:
-      fail-fast: false
-      max-parallel: 2
-      matrix:
-        include:
-          - os: ubuntu-latest
-            platform: linux
-            architecture: x64
-          - os: ubuntu-24.04-arm
-            platform: linux
-            architecture: arm64
-          - os: windows-latest
-            platform: win32
-            architecture: x64
-    runs-on: ${{ matrix.os }}
-    timeout-minutes: 10
-    env:
-      NODE_OPTIONS: "--max-old-space-size=1024"
-      UV_THREADPOOL_SIZE: "2"
-    steps:
-      - uses: actions/checkout@v4
-      - uses: actions/setup-node@v4
-        with:
-          node-version-file: .nvmrc
-          cache: npm
-      - name: Verify native runtime identity
-        env:
-          EXPECTED_CI_PLATFORM: ${{ matrix.platform }}
-          EXPECTED_CI_ARCHITECTURE: ${{ matrix.architecture }}
-        run: >-
-          node -e "const assert = require('node:assert/strict');
-          assert.equal(process.platform, process.env.EXPECTED_CI_PLATFORM);
-          assert.equal(process.arch, process.env.EXPECTED_CI_ARCHITECTURE);
-          console.log(JSON.stringify({ platform: process.platform, architecture: process.arch, node: process.version }));"
-      - run: npm ci
-      - name: Verify real Node Inspector discovery and observation
-        run: npm run verify:inspector
-
   windows-curated:
     name: Windows capability and package lane
     needs: [changes, windows-native-build]
@@ -475,6 +442,12 @@ jobs:
           tests/process-global/updateMaintenance.test.ts
           tests/conformance/providers/ghidra/realGhidraWindowsWorkflow.test.ts
       - run: npm run verify:windows-native
+      - name: Verify real Node Inspector discovery and observation
+        timeout-minutes: 10
+        env:
+          NODE_OPTIONS: "--max-old-space-size=1024"
+          UV_THREADPOOL_SIZE: "2"
+        run: npm run verify:inspector
       - run: npm run verify:package:windows
       - name: Verify native directory identity on Node 24
         run: >-
diff --git a/tests/boundary/filesystem/ciChangeScope.test.ts b/tests/boundary/filesystem/ciChangeScope.test.ts
new file mode 100644
index 000000000..107ba8809
--- /dev/null
+++ b/tests/boundary/filesystem/ciChangeScope.test.ts
@@ -0,0 +1,203 @@
+import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+import { expect, it } from "vitest";
+import { parse } from "yaml";
+import { z } from "zod";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import {
+  executeWorkflowFixture as execFileAsync,
+  workflowGit as git,
+} from "../../support/workflowGit.js";
+
+const workflowSchema = z.object({
+  jobs: z.object({
+    changes: z.object({
+      steps: z.array(
+        z.object({ id: z.string().optional(), run: z.string().optional() }),
+      ),
+    }),
+  }),
+});
+
+async function commit(directory: string) {
+  await git(directory, ["add", "."]);
+  await git(directory, ["commit", "-m", "fix: fixture change"]);
+  return git(directory, ["rev-parse", "HEAD"]);
+}
+
+async function change(
+  directory: string,
+  paths: readonly string[],
+  content = "Changed fixture content\n",
+) {
+  for (const path of paths) {
+    const file = join(directory, path);
+    await mkdir(dirname(file), { recursive: true });
+    await writeFile(file, content);
+  }
+  return commit(directory);
+}
+
+async function fixture() {
+  const directory = await createTestTempDirectory("rea-ci-scope-");
+  await git(directory, ["init", "--initial-branch=main"]);
+  const base = await change(
+    directory,
+    ["src/provider.ts", "README.md"],
+    "Initial fixture content\n",
+  );
+  return { directory, base };
+}
+
+async function classify(
+  directory: string,
+  base: string,
+  head: string,
+  event = "pull_request",
+) {
+  const workflow = workflowSchema.parse(
+    parse(
+      await readFile(
+        new URL("../../../.github/workflows/ci.yml", import.meta.url),
+        "utf8",
+      ),
+    ),
+  );
+  const command = z
+    .string()
+    .parse(
+      workflow.jobs.changes.steps.find((step) => step.id === "package")?.run,
+    );
+  const output = join(directory, "scope-output");
+  await writeFile(output, "");
+  await execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
+    cwd: directory,
+    env: {
+      ...process.env,
+      BASE_SHA: base,
+      HEAD_SHA: head,
+      GITHUB_EVENT_NAME: event,
+      GITHUB_OUTPUT: output,
+    },
+  });
+  return readFile(output, "utf8");
+}
+
+it("keeps every translated root README and authored guide on the documentation lane", async () => {
+  const { directory, base } = await fixture();
+  const readmes = (await readdir(new URL("../../../", import.meta.url))).filter(
+    (name) => /^README(?:_.*)?\.md$/u.test(name),
+  );
+  expect(readmes).toContain("README.md");
+  const head = await change(directory, [
+    ...readmes,
+    "docs/guide.md",
+    "AGENTS.md",
+    "CONTRIBUTING.md",
+  ]);
+  expect(await classify(directory, base, head)).toBe("required=false\n");
+});
+
+it("does not charge a documentation PR for unrelated implementation updates on main", async () => {
+  const { directory, base } = await fixture();
+  await git(directory, ["switch", "-c", "docs/change"]);
+  const head = await change(directory, ["README_zh-TW.md"]);
+  await git(directory, ["switch", "main"]);
+  const advancedBase = await change(directory, ["src/anotherProvider.ts"]);
+  expect(advancedBase).not.toBe(base);
+  expect(await classify(directory, advancedBase, head)).toBe(
+    "required=false\n",
+  );
+});
+
+it.each([
+  "src/README.md",
+  "README.md.ts",
+  "package.json",
+  "bridge/ghidra/provider.py",
+  "tests/fixture.test.ts",
+  ".github/workflows/ci.yml",
+  "unknown-file",
+])(
+  "retains complete checks when documentation is mixed with %s",
+  async (path) => {
+    const { directory, base } = await fixture();
+    const head = await change(directory, ["README.md", path]);
+    expect(await classify(directory, base, head)).toBe("required=true\n");
+  },
+);
+
+it("retains complete checks when implementation is renamed into documentation", async () => {
+  const { directory, base } = await fixture();
+  await mkdir(join(directory, "docs"));
+  await rename(
+    join(directory, "src/provider.ts"),
+    join(directory, "docs/provider.md"),
+  );
+  const head = await commit(directory);
+  expect(await classify(directory, base, head)).toBe("required=true\n");
+});
+
+it("retains the complete main-push baseline even for documentation", async () => {
+  const { directory, base } = await fixture();
+  const head = await change(directory, ["README_ja.md"]);
+  expect(await classify(directory, base, head, "push")).toBe("required=true\n");
+});
+
+it("fails classification rather than treating an invalid Git comparison as a scope", async () => {
+  const { directory, base } = await fixture();
+  await expect(classify(directory, "missing-ref", base)).rejects.toMatchObject({
+    code: 128,
+  });
+  expect(await readFile(join(directory, "scope-output"), "utf8")).toBe("");
+});
+
+it("retains native Inspector verification on every documented package host", async () => {
+  const stepSchema = z.object({
+    run: z.string().optional(),
+    if: z.string().optional(),
+  });
+  const steps = z.array(stepSchema);
+  const workflow = z
+    .object({
+      jobs: z.object({
+        "package-e2e": z.object({
+          strategy: z.object({
+            matrix: z.object({
+              include: z.array(
+                z.object({ platform: z.string(), architecture: z.string() }),
+              ),
+            }),
+          }),
+          steps,
+        }),
+        "windows-curated": z.object({ steps }),
+      }),
+    })
+    .parse(
+      parse(
+        await readFile(
+          new URL("../../../.github/workflows/ci.yml", import.meta.url),
+          "utf8",
+        ),
+      ),
+    );
+  const packageLane = workflow.jobs["package-e2e"];
+  const packageInspector = stepSchema.parse(
+    packageLane.steps.find((step) => step.run === "npm run verify:inspector"),
+  );
+  expect(packageInspector.if).toBeUndefined();
+  expect(
+    packageLane.strategy.matrix.include
+      .map(({ platform, architecture }) => `${platform}/${architecture}`)
+      .sort(),
+  ).toEqual(["darwin/arm64", "darwin/x64", "linux/arm64", "linux/x64"]);
+  const windowsInspector = stepSchema.parse(
+    workflow.jobs["windows-curated"].steps.find(
+      (step) => step.run === "npm run verify:inspector",
+    ),
+  );
+  expect(windowsInspector.if).toBeUndefined();
+});
diff --git a/tests/boundary/filesystem/releaseCheckpoint.test.ts b/tests/boundary/filesystem/releaseCheckpoint.test.ts
index e7dc61e41..226fbb37c 100644
--- a/tests/boundary/filesystem/releaseCheckpoint.test.ts
+++ b/tests/boundary/filesystem/releaseCheckpoint.test.ts
@@ -1,44 +1,19 @@
-import { execFile } from "node:child_process";
 import { mkdir, readFile, writeFile } from "node:fs/promises";
 import { join } from "node:path";
 import { fileURLToPath } from "node:url";
-import { promisify } from "node:util";
 import { expect, it } from "vitest";
 import { z } from "zod";
 import { parse } from "yaml";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import {
+  executeWorkflowFixture as execFileAsync,
+  workflowGit as git,
+} from "../../support/workflowGit.js";
 
-const execFileAsync = promisify(execFile);
 const verifier = fileURLToPath(
   new URL("../../../scripts/verify-release-checkpoint.mjs", import.meta.url),
 );
 
-async function git(
-  directory: string,
-  args: string[],
-  date = "2026-01-04T00:00:00Z",
-) {
-  const result = await execFileAsync(
-    "git",
-    [
-      "-c",
-      "user.name=REA fixture",
-      "-c",
-      "user.email=fixture@example.invalid",
-      "-c",
-      "commit.gpgsign=false",
-      "-c",
-      `core.hooksPath=${join(directory, "no-hooks")}`,
-      ...args,
-    ],
-    {
-      cwd: directory,
-      env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date },
-    },
-  );
-  return result.stdout.trim();
-}
-
 async function metadata(
   directory: string,
   version: string,
diff --git a/tests/support/workflowGit.ts b/tests/support/workflowGit.ts
new file mode 100644
index 000000000..c89d2a4be
--- /dev/null
+++ b/tests/support/workflowGit.ts
@@ -0,0 +1,33 @@
+import { execFile } from "node:child_process";
+import { join } from "node:path";
+import { promisify } from "node:util";
+
+/** Execute a fixture command while retaining its output and native exit status. */
+export const executeWorkflowFixture = promisify(execFile);
+
+/** Run fixture Git commands with deterministic dates and no workstation hooks. */
+export async function workflowGit(
+  directory: string,
+  args: readonly string[],
+  date = "2026-01-04T00:00:00Z",
+) {
+  const result = await executeWorkflowFixture(
+    "git",
+    [
+      "-c",
+      "user.name=REA fixture",
+      "-c",
+      "user.email=fixture@example.invalid",
+      "-c",
+      "commit.gpgsign=false",
+      "-c",
+      `core.hooksPath=${join(directory, "no-hooks")}`,
+      ...args,
+    ],
+    {
+      cwd: directory,
+      env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date },
+    },
+  );
+  return result.stdout.trim();
+}

From 6c9161d61745e242643f224ce49e7468143a15f3 Mon Sep 17 00:00:00 2001
From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:28:43 +0800
Subject: [PATCH 052/189] docs: explain CI scope and native runner reuse
 (#1348)

---
 docs/testing.md | 28 +++++++++++++++++++++-------
 1 file changed, 21 insertions(+), 7 deletions(-)

diff --git a/docs/testing.md b/docs/testing.md
index 76d09d7af..c0846b184 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -598,6 +598,17 @@ not make native host acceptance unavailable.
 
 ## Native platform baseline in CI
 
+Pull requests that change only root `README*.md` files, `docs/`, `AGENTS.md`,
+or `CONTRIBUTING.md` run formatting and generated-document validation without
+the source-test shards or native package lanes. Classification compares the PR
+head with its merge base, so later base-branch changes do not expand that scope.
+The required static and coverage aggregate jobs remain present and fail if
+classification fails. Mixed changes, unknown paths and CI configuration changes
+retain full checks. Main pushes retain the full baseline, including after
+documentation merges; newer commits cancel superseded CI for the same PR or
+main branch. Release publication has its own concurrency group and retains its
+package verification and public-registry canary.
+
 CI exercises the pinned Node.js runtime on native hosted runners:
 
 | Host                  | Runner             | Baseline checks                                                                          |
@@ -608,17 +619,20 @@ CI exercises the pinned Node.js runtime on native hosted runners:
 | macOS 15 x64          | `macos-15-intel`   | Installed package and real Node Inspector CLI/MCP                                        |
 | Windows x64           | `windows-latest`   | Curated capabilities, native controls, installed package and real Node Inspector CLI/MCP |
 
-Package and Inspector matrices assert the actual Node platform/architecture
-before verification and record those values with the Node version. Each matrix
+Package lanes assert the actual Node platform/architecture before verification
+and record those values with the Node version. The four-host package matrix
 runs at most two jobs concurrently with explicit timeouts and Node heap/thread
-limits. Package checks cover installation, CLI/MCP discovery, target-free
+limits; Windows retains its curated capability lane. Package checks cover
+installation, CLI/MCP discovery, target-free
 analysis, configuration backups/recovery, Evidence and owned lifecycle; Inspector
 checks execute source-owned loopback targets and special filename cases.
 
-macOS uses one OS version with one native baseline job per architecture. Each job
-runs package and Inspector checks after a single dependency installation. The
-separate Inspector matrix covers Linux and Windows; Apple artifact checks retain
-their own macOS 15 arm64 job for Xcode-dependent workflows.
+Each native package host runs package and Inspector checks on the same runner
+after a single dependency installation. macOS uses one OS version with one
+native baseline job per architecture. Windows runs Inspector with its curated
+capability/package checks before switching Node versions for directory-identity
+regressions. Inspector steps retain a ten-minute deadline; Apple artifact checks
+retain their own macOS 15 arm64 job for Xcode-dependent workflows.
 
 These native baseline checks complement the Linux source-test shards and the
 separate Apple-artifact and real-provider lanes. Actual Hopper, Ghidra, IDA,

From f6cfbfcc554ff24173dd7ad5333e8e26ab9c962d Mon Sep 17 00:00:00 2001
From: Lucien <164857476+dakjdakd@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:33:56 +0800
Subject: [PATCH 053/189] fix(browser): release attached viewport overrides
 without resizing the external page

Co-authored-by: dakjdakd <164857476+dakjdakd@users.noreply.github.com>
---
 scripts/lib/browser-scenario-environment-e2e.mjs | 16 +++++++++++-----
 src/browser/PlaywrightScenarioBrowser.ts         |  8 +++-----
 2 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/scripts/lib/browser-scenario-environment-e2e.mjs b/scripts/lib/browser-scenario-environment-e2e.mjs
index 1804402f3..0528d358a 100644
--- a/scripts/lib/browser-scenario-environment-e2e.mjs
+++ b/scripts/lib/browser-scenario-environment-e2e.mjs
@@ -126,17 +126,22 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
     });
     try {
       await client.connect(transport);
+      const definition = (await client.listTools()).tools.find(
+        ({ name }) => name === "capture_browser_scenario",
+      );
+      assert.ok(definition, "Scenario tool is absent from the current catalog");
       assertCapture(
         requireMcpEvidenceResult(
-          await client.callTool({
-            name: "capture_browser_scenario",
-            arguments: scenario,
-          }),
+          await client.callTool(
+            { name: "capture_browser_scenario", arguments: scenario },
+            { toolDefinition: definition },
+          ),
           "capture_browser_scenario",
         ),
       );
       await verifyConcurrentMcpCapture({
         client,
+        definition,
         connection,
         endpoint,
         targetId,
@@ -198,6 +203,7 @@ export async function verifyScenarioEnvironment(endpoint, targetId, origin) {
 
 const verifyConcurrentMcpCapture = async ({
   client,
+  definition,
   connection,
   endpoint,
   targetId,
@@ -226,7 +232,7 @@ const verifyConcurrentMcpCapture = async ({
   const callTool = (arguments_, signal) => {
     const pending = client.callTool(
       { name: "capture_browser_scenario", arguments: arguments_ },
-      { signal, timeout: 60_000 },
+      { signal, timeout: 60_000, toolDefinition: definition },
     );
     void pending.catch(() => {});
     pendingCalls.push(pending);
diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts
index 88fdda0f8..cd2d5a65a 100644
--- a/src/browser/PlaywrightScenarioBrowser.ts
+++ b/src/browser/PlaywrightScenarioBrowser.ts
@@ -288,11 +288,8 @@ const configureAttachedEnvironment = async (
   environment: BrowserScenario["environment"],
   signal: AbortSignal | undefined,
 ): Promise => {
-  await page.setViewportSize({
-    width: environment.viewport.width,
-    height: environment.viewport.height,
-  });
-  throwIfScenarioCancelled(signal);
+  // setViewportSize also resizes the external browser window. The scenario's
+  // CDP metrics override below supplies the viewport and expires on disconnect.
   await page.emulateMedia({
     colorScheme: environment.color_scheme,
     reducedMotion: environment.reduced_motion,
@@ -307,6 +304,7 @@ const configureAttachedEnvironment = async (
     height: environment.viewport.height,
     deviceScaleFactor: environment.viewport.device_scale_factor,
     mobile: false,
+    dontSetVisibleSize: true,
   });
   throwIfScenarioCancelled(signal);
   await session.send("Emulation.setLocaleOverride", {

From 1ac8389c5c1f75faf8d7f2f3faf2f24febad5fea Mon Sep 17 00:00:00 2001
From: Lucien <164857476+dakjdakd@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:38:33 +0800
Subject: [PATCH 054/189] test(artifacts): verify extraction races with real
 filesystem changes

Co-authored-by: dakjdakd <164857476+dakjdakd@users.noreply.github.com>
---
 .github/workflows/ci.yml                      |  1 +
 ...actProvider.extractionCompleteness.test.ts | 81 +++++++++++++------
 2 files changed, 58 insertions(+), 24 deletions(-)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 97025afe7..6d03dc87e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -415,6 +415,7 @@ jobs:
           tests/boundary/filesystem/binaryTarget.test.ts
           tests/boundary/filesystem/safeOutputTree.test.ts
           tests/boundary/providers/native/artifactProvider.archiveSafety.test.ts
+          tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
           tests/boundary/filesystem/setupUnavailableProvider.test.ts
           tests/boundary/filesystem/windowsNpxRegistration.test.ts
           tests/boundary/filesystem/webScriptManifestPaths.test.ts
diff --git a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
index e5994c79a..778a80f33 100644
--- a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
+++ b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
@@ -1,11 +1,12 @@
+import { createHash } from "node:crypto";
+import { watch } from "node:fs";
 import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
-import { join } from "node:path";
+import { basename, dirname, join } from "node:path";
 
 import { createPackage, createPackageWithOptions } from "@electron/asar";
-import { expect, it, onTestFinished, vi } from "vitest";
+import { expect, it, onTestFinished } from "vitest";
 
 import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
-import { SafeOutputTree } from "../../../../src/artifacts/SafeOutputTree.js";
 import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
 import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
 import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -17,10 +18,11 @@ it.each(["file", "directory"] as const)(
     const source = join(root, "source");
     await mkdir(join(source, "z"), { recursive: true });
     // Equal bytes share an artifact node, but both occurrences must be copied.
-    await writeFile(join(source, "a.txt"), "same bytes\n");
-    await writeFile(join(source, "z", "missing.txt"), "same bytes\n");
+    const bytes = Buffer.alloc(8 * 1024 * 1024, "same bytes\n");
+    await writeFile(join(source, "a.txt"), bytes);
+    await writeFile(join(source, "z", "missing.txt"), bytes);
     const output = join(root, "output");
-    afterInventory(async () => {
+    const changed = afterInventory(output, async () => {
       await rm(
         removedKind === "file"
           ? join(source, "z", "missing.txt")
@@ -30,18 +32,36 @@ it.each(["file", "directory"] as const)(
     });
 
     const result = await extract(source, output);
+    await changed();
     if (result.ok) throw new Error("Incomplete extraction must fail");
-    expect(projectAnalysisError(result.error)).toMatchObject({
+    const projected = projectAnalysisError(result.error);
+    expect(projected).toMatchObject({
       code: "artifact_operation_failed",
       details: {
         operation: "extract_artifact",
+      },
+    });
+    // A directory already returned by readdir can disappear before its stat.
+    // That earlier reader failure retains ENOENT instead of reaching the final
+    // completeness check. Both paths must reject publication and roll back.
+    if (removedKind === "directory" && projected.details?.reason === "io") {
+      expect(projected.details).toMatchObject({
+        reason: "io",
+        detail: `Could not inspect entry at ${join(source, "z")} (ENOENT)`,
+      });
+    } else {
+      expect(projected.details).toMatchObject({
         reason: "integrity",
         detail:
           "Inventoried regular artifact entries were not materialized: z/missing.txt",
-      },
-    });
+      });
+    }
     await expect(access(output)).rejects.toThrow();
-    expect(await readFile(join(source, "a.txt"), "utf8")).toBe("same bytes\n");
+    expect(
+      createHash("sha256")
+        .update(await readFile(join(source, "a.txt")))
+        .digest("hex"),
+    ).toBe(createHash("sha256").update(bytes).digest("hex"));
   },
 );
 
@@ -49,12 +69,16 @@ it("still refuses a regular file added after inventory and rolls back", async ()
   const root = await createTestTempDirectory("rea-extract-added-");
   const source = join(root, "source");
   await mkdir(source);
-  await writeFile(join(source, "a.txt"), "original\n");
+  await writeFile(
+    join(source, "a.txt"),
+    Buffer.alloc(8 * 1024 * 1024, "original\n"),
+  );
   const output = join(root, "output");
-  afterInventory(async () => {
+  const changed = afterInventory(output, async () => {
     await writeFile(join(source, "z.txt"), "new\n");
   });
   const result = await extract(source, output);
+  await changed();
   if (result.ok) throw new Error("Changed inventory must fail");
   expect(projectAnalysisError(result.error)).toMatchObject({
     details: {
@@ -136,18 +160,27 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
   await expect(access(activeOutput)).rejects.toThrow();
 });
 
-// Synchronize a real filesystem change after the actual inventory scan. The
-// production reader, writes, failure translation and rollback all remain real.
-const afterInventory = (change: () => Promise): void => {
-  const create = SafeOutputTree.create;
-  const hook = vi
-    .spyOn(SafeOutputTree, "create")
-    .mockImplementationOnce(async (...args) => {
-      const output = await create(...args);
-      await change();
-      return output;
-    });
-  onTestFinished(() => hook.mockRestore());
+// The real destination is created only after inventory. A streamed first file
+// leaves time to mutate a later entry without replacing any production method.
+const afterInventory = (output: string, change: () => Promise) => {
+  let mutation:
+    | Promise<{ ok: true } | { ok: false; cause: unknown }>
+    | undefined;
+  const watcher = watch(dirname(output), (_event, filename) => {
+    if (filename !== basename(output) || mutation !== undefined) return;
+    watcher.close();
+    mutation = change().then(
+      () => ({ ok: true as const }),
+      (cause: unknown) => ({ ok: false as const, cause }),
+    );
+  });
+  onTestFinished(() => watcher.close());
+  return async () => {
+    if (mutation === undefined)
+      throw new Error("Extraction destination was not observed");
+    const result = await mutation;
+    if (!result.ok) throw result.cause;
+  };
 };
 
 const extract = (source: string, output: string) =>

From 2793672ee2a575f97a8011c7fec5288098cdd5d1 Mon Sep 17 00:00:00 2001
From: Yi-111-a 
Date: Sat, 10 Oct 2026 01:49:23 +0800
Subject: [PATCH 055/189] fix(skill): pin packaged commands to the shipping
 package version

The generated skill rewrote `rea-agents@latest` to the version it ships with, so a pinned install no longer needs a local edit that `doctor --skill` reports as stale.

Co-Authored-By: OpenCode 
---
 scripts/generate-skill-metadata.mjs           | 19 +++++++++++++-----
 .../filesystem/dependencyInstall.test.ts      | 10 ++++++++--
 .../filesystem/generatedSkill.test.ts         | 20 +++++++++++++++++++
 3 files changed, 42 insertions(+), 7 deletions(-)

diff --git a/scripts/generate-skill-metadata.mjs b/scripts/generate-skill-metadata.mjs
index 490976fb5..931163e3b 100644
--- a/scripts/generate-skill-metadata.mjs
+++ b/scripts/generate-skill-metadata.mjs
@@ -16,8 +16,12 @@ const check = arguments_.has("--check");
 const current = (
   await readFile(join(sourceRoot, "SKILL.md"), "utf8")
 ).replaceAll("\r\n", "\n");
+const cacheBust = String(Date.now());
 const { CATALOG_IDENTITY } = await import(
-  `${pathToFileURL(join(root, "dist/catalogIdentity.js")).href}?${String(Date.now())}`
+  `${pathToFileURL(join(root, "dist/catalogIdentity.js")).href}?${cacheBust}`
+);
+const { PACKAGE_METADATA } = await import(
+  `${pathToFileURL(join(root, "dist/generatedPackageMetadata.js")).href}?${cacheBust}`
 );
 if (/^\s{2}(?:tool_count|catalog_digest):/mu.test(current))
   throw new Error(
@@ -26,10 +30,15 @@ if (/^\s{2}(?:tool_count|catalog_digest):/mu.test(current))
 const versionLine = /^ {2}version: "[^"\r\n]+"$/mu;
 if (!versionLine.test(current))
   throw new Error("Missing authored skill version");
-const source = current.replace(
-  versionLine,
-  `$&\n  tool_count: ${String(CATALOG_IDENTITY.counts.mcp_tools)}`,
-);
+// A shipped skill must run the version it ships with, not whatever `@latest` resolves to.
+const latestSpecifier = `${PACKAGE_METADATA.name}@latest`;
+const pinnedSpecifier = `${PACKAGE_METADATA.name}@${PACKAGE_METADATA.version}`;
+const source = current
+  .replace(
+    versionLine,
+    `$&\n  tool_count: ${String(CATALOG_IDENTITY.counts.mcp_tools)}`,
+  )
+  .replaceAll(latestSpecifier, pinnedSpecifier);
 const paths = await filePaths(sourceRoot);
 // Rebuild this owned output directory so removed references cannot survive a build.
 if (!check) await rm(outputRoot, { recursive: true, force: true });
diff --git a/tests/boundary/filesystem/dependencyInstall.test.ts b/tests/boundary/filesystem/dependencyInstall.test.ts
index 18eb5f95a..967d1a839 100644
--- a/tests/boundary/filesystem/dependencyInstall.test.ts
+++ b/tests/boundary/filesystem/dependencyInstall.test.ts
@@ -100,7 +100,7 @@ describe("dependency install freshness", () => {
   it("checks installed dependencies before restoring a cached build", async () => {
     const root = await createBuildCacheFixture();
     const seeded = await runNpm(root, ["run", "build:cached"]);
-    expect(seeded.status, seeded.stderr).toBe(0);
+    expect(seeded.status, `${seeded.stdout}${seeded.stderr}`).toBe(0);
 
     const rootLock = asRecord(
       JSON.parse(await readFile(join(root, "package-lock.json"), "utf8")),
@@ -189,7 +189,13 @@ const createBuildCacheFixture = async (): Promise => {
   );
   await writeFile(
     join(root, "scripts/cache-fixture-build.mjs"),
-    'import { mkdir, writeFile } from "node:fs/promises"; await mkdir("dist", { recursive: true }); await writeFile("dist/cache-fixture.js", "built"); await writeFile("dist/catalogIdentity.js", "export const CATALOG_IDENTITY = { counts: { mcp_tools: 1 } };\\n");\n',
+    `import { mkdir, readFile, writeFile } from "node:fs/promises";
+const { name, version } = JSON.parse(await readFile("package.json", "utf8"));
+await mkdir("dist", { recursive: true });
+await writeFile("dist/cache-fixture.js", "built");
+await writeFile("dist/catalogIdentity.js", "export const CATALOG_IDENTITY = { counts: { mcp_tools: 1 } };\\n");
+await writeFile("dist/generatedPackageMetadata.js", "export const PACKAGE_METADATA = " + JSON.stringify({ name, version }) + ";\\n");
+`,
   );
   await createNodeModulesLinks(root);
   await writeFile(
diff --git a/tests/boundary/filesystem/generatedSkill.test.ts b/tests/boundary/filesystem/generatedSkill.test.ts
index c5db95c1a..f35e0abb6 100644
--- a/tests/boundary/filesystem/generatedSkill.test.ts
+++ b/tests/boundary/filesystem/generatedSkill.test.ts
@@ -26,6 +26,10 @@ async function fixture(eol = "\n") {
   await mkdir(join(sourceRoot, "references"), { recursive: true });
   await mkdir(join(root, "dist"));
   await writeFile(join(root, "package.json"), '{"type":"module"}\n');
+  await writeFile(
+    join(root, "dist/generatedPackageMetadata.js"),
+    'export const PACKAGE_METADATA = { name: "rea-agents", version: "6.2.0" };\n',
+  );
   await writeFile(join(sourceRoot, "SKILL.md"), authored.replaceAll("\n", eol));
   await writeFile(
     join(sourceRoot, "references/guide.md"),
@@ -111,6 +115,22 @@ it("rejects missing, stale, and extra packaged references and removes deleted so
   await f.generate("--check");
 });
 
+it("pins authored `@latest` commands to the packaged version", async () => {
+  const f = await fixture();
+  await writeFile(
+    join(f.sourceRoot, "SKILL.md"),
+    authored.replace(
+      "Inspect the caller-selected artifact.",
+      "Run `npx -y rea-agents@latest doctor --json` first.",
+    ),
+  );
+  await f.generate();
+  const generated = await readFile(join(f.outputRoot, "SKILL.md"), "utf8");
+  expect(generated).toContain("npx -y rea-agents@6.2.0 doctor --json");
+  expect(generated).not.toContain("rea-agents@latest");
+  await f.generate("--check");
+});
+
 it("rejects catalog-dependent metadata in the authored source", async () => {
   const f = await fixture();
   await writeFile(

From db171be6e570fd1261a30d711e4da2d17de85a93 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:53:46 +0800
Subject: [PATCH 056/189] fix(javascript): preserve agreeing module provenance

---
 ...aScriptApplicationModuleProvenance.test.ts | 70 +++++++++++++++++++
 .../javascript/javascriptSemanticValues.ts    | 15 +++-
 2 files changed, 82 insertions(+), 3 deletions(-)
 create mode 100644 src/application/javascript/JavaScriptApplicationModuleProvenance.test.ts

diff --git a/src/application/javascript/JavaScriptApplicationModuleProvenance.test.ts b/src/application/javascript/JavaScriptApplicationModuleProvenance.test.ts
new file mode 100644
index 000000000..ba8e168eb
--- /dev/null
+++ b/src/application/javascript/JavaScriptApplicationModuleProvenance.test.ts
@@ -0,0 +1,70 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import { analyzeJavaScriptApplication } from "./JavaScriptApplicationService.js";
+
+it.each([
+  {
+    expression:
+      'flag ? require("./dependency.js").value : require("./dependency.js").value',
+    resolved: true,
+  },
+  {
+    expression:
+      'require("./dependency.js").value || require("./dependency.js").value',
+    resolved: true,
+  },
+  {
+    expression: 'flag ? require("./dependency.js").value : localValue',
+    resolved: false,
+  },
+  {
+    expression: 'require("./dependency.js").value ?? localValue',
+    resolved: false,
+  },
+])(
+  "preserves export provenance for $expression",
+  async ({ expression, resolved }) => {
+    const root = await createTestTempDirectory("rea-js-module-provenance-");
+    await Promise.all([
+      writeFile(
+        join(root, "app.js"),
+        `const selected = ${expression};\nexport { selected };\n`,
+      ),
+      writeFile(join(root, "dependency.js"), "exports.value = 1;\n"),
+    ]);
+
+    const result = await analyzeJavaScriptApplication({
+      input_path: root,
+      format: "directory",
+    });
+    if (!result.ok) throw result.error;
+    const analysis = javascriptApplicationAnalysisResultSchema.parse(
+      JSON.parse(JSON.stringify(result.value.normalized_result)),
+    );
+
+    const exportImports = analysis.graph.edges.filter(
+      ({ relation, properties }) =>
+        relation === "imports" && properties.exported_name === "selected",
+    );
+    if (!resolved) {
+      expect(exportImports).toEqual([]);
+      return;
+    }
+    expect(exportImports).toContainEqual(
+      expect.objectContaining({
+        relation: "imports",
+        properties: expect.objectContaining({
+          specifier: "./dependency.js",
+          imported_path: ["value"],
+          resolved_path: "dependency.js",
+          resolution_status: "resolved",
+        }),
+      }),
+    );
+  },
+);
diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts
index 39380a9c0..2c0b855a4 100644
--- a/src/domain/javascript/javascriptSemanticValues.ts
+++ b/src/domain/javascript/javascriptSemanticValues.ts
@@ -604,11 +604,20 @@ const provenanceForExpression = (
       provenanceForExpression(left, nestedContext(context)),
       provenanceForExpression(right, nestedContext(context)),
     ];
-    const origins = candidates.flatMap((candidate) => candidate.origins);
+    const origins = uniqueSemanticOrigins(
+      candidates.flatMap((candidate) => candidate.origins),
+    );
+    const allModuleOrigins = candidates.every(
+      ({ status }) => status === "module",
+    );
+    if (allModuleOrigins && origins.length === 1)
+      return semanticOriginsProvenance(origins);
     return origins.length > 0
       ? semanticAmbiguousProvenance(
-          uniqueSemanticOrigins(origins),
-          "Multiple module origins.",
+          origins,
+          allModuleOrigins
+            ? "Multiple module origins."
+            : "Conditional provenance includes a non-module alternative.",
         )
       : semanticUnresolvedProvenance(
           "unknown",

From f7cf4c890d4b9c70b1f56e6c627b44a59e58fd73 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:53:59 +0800
Subject: [PATCH 057/189] fix(cli): classify oversized JSON inputs

---
 src/cliJsonInput.ts                           |  70 ++++++++++--
 src/contracts/errorSchemas.ts                 |   4 +-
 .../boundary/filesystem/cliJsonInput.test.ts  | 100 +++++++++++++++++-
 3 files changed, 162 insertions(+), 12 deletions(-)

diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts
index 5c4397bf6..74dd30bc9 100644
--- a/src/cliJsonInput.ts
+++ b/src/cliJsonInput.ts
@@ -1,10 +1,14 @@
+import { constants as bufferConstants } from "node:buffer";
 import { resolve } from "node:path";
 
 import {
   NonRegularFileReadError,
   readRegularFile,
 } from "./application/RegularFileRead.js";
-import { AnalysisInputError } from "./domain/analysisErrorCore.js";
+import {
+  AnalysisInputError,
+  AnalysisResourceConstraintError,
+} from "./domain/analysisErrorCore.js";
 import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
 import type { JsonValue } from "./domain/jsonValue.js";
 import { safeParseJson } from "./domain/safeJson.js";
@@ -18,14 +22,16 @@ export const parseCliJsonInput = async (
   | { readonly ok: false; readonly error: JsonValue }
 > => {
   const inline = parseJson(value);
-  if (inline !== undefined) return { ok: true, value: inline };
+  if (inline.kind === "valid") return { ok: true, value: inline.value };
+  if (inline.kind === "too-large")
+    return jsonTooLargeError(undefined, operation);
   try {
     // Read raw bytes so invalid UTF-8 is rejected by parseJson instead of
     // being silently replaced by lossy "utf8" decoding.
     const parsed = parseJson(await readRegularFile(value));
-    return parsed === undefined
-      ? jsonFileError(value, operation, "invalid-json")
-      : { ok: true, value: parsed };
+    if (parsed.kind === "valid") return { ok: true, value: parsed.value };
+    if (parsed.kind === "too-large") return jsonTooLargeError(value, operation);
+    return jsonFileError(value, operation, "invalid-json");
   } catch (cause: unknown) {
     if (
       ["{", "["].includes(value.trimStart()[0] ?? "") &&
@@ -87,7 +93,12 @@ const cannotBeAnExistingFile = (cause: unknown): boolean =>
 const hasExplicitJsonFileExtension = (value: string): boolean =>
   value.toLowerCase().endsWith(".json");
 
-const parseJson = (value: string | Uint8Array): unknown => {
+type JsonParseResult =
+  | { readonly kind: "valid"; readonly value: unknown }
+  | { readonly kind: "invalid" }
+  | { readonly kind: "too-large" };
+
+const parseJson = (value: string | Uint8Array): JsonParseResult => {
   let text: string;
   if (typeof value === "string") {
     text = value;
@@ -98,15 +109,24 @@ const parseJson = (value: string | Uint8Array): unknown => {
         ignoreBOM: true,
       }).decode(value);
     } catch (cause: unknown) {
-      // Decoding failure means the bytes are not valid UTF-8 JSON input.
-      void cause;
-      return undefined;
+      return isStringLengthLimit(cause)
+        ? { kind: "too-large" }
+        : { kind: "invalid" };
     }
   }
   const parsed = safeParseJson(text);
-  return parsed.ok ? parsed.value : undefined;
+  if (parsed.ok) return { kind: "valid", value: parsed.value };
+  return isStringLengthLimit(parsed.cause)
+    ? { kind: "too-large" }
+    : { kind: "invalid" };
 };
 
+const isStringLengthLimit = (cause: unknown): boolean =>
+  cause instanceof Error &&
+  /cannot create a string longer than|invalid string length/i.test(
+    cause.message,
+  );
+
 const inputError = (operation: string): JsonValue => ({
   error: "Application workflow failed",
   ...projectAnalysisError(
@@ -157,3 +177,33 @@ const readFailureIssue = (path: string | undefined, cause: unknown) => {
         : `The JSON input file could not be read${code}: ${path ?? ""}`,
   };
 };
+
+const jsonTooLargeError = (
+  path: string | undefined,
+  operation: string,
+): { readonly ok: false; readonly error: JsonValue } => {
+  const projection = projectAnalysisError(
+    new AnalysisResourceConstraintError(
+      operation,
+      "memory",
+      `The JSON input exceeds this Node.js runtime's maximum string length (${bufferConstants.MAX_STRING_LENGTH} UTF-16 code units) and cannot be parsed as one value.`,
+      {
+        boundary: "cli-json-input",
+        max_string_code_units: bufferConstants.MAX_STRING_LENGTH,
+      },
+      {
+        remediationAction:
+          "Split the JSON into smaller inputs or rerun its producer on a smaller subset, then retry.",
+      },
+    ),
+  );
+  return {
+    ok: false,
+    error: {
+      error: "Application workflow failed",
+      ...projection,
+      ...(path === undefined ? {} : { input_path: path }),
+      input_reason: "too-large",
+    },
+  };
+};
diff --git a/src/contracts/errorSchemas.ts b/src/contracts/errorSchemas.ts
index a535f6abf..812dc89d6 100644
--- a/src/contracts/errorSchemas.ts
+++ b/src/contracts/errorSchemas.ts
@@ -73,7 +73,9 @@ export const analysisCliErrorEnvelopeSchema = z
   .object({
     error: z.string().min(1),
     input_path: z.string().optional(),
-    input_reason: z.enum(["invalid-json", "read-failed"]).optional(),
+    input_reason: z
+      .enum(["invalid-json", "read-failed", "too-large"])
+      .optional(),
   })
   .passthrough()
   .superRefine((value, context) => {
diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts
index d75dac4e3..273168fdb 100644
--- a/tests/boundary/filesystem/cliJsonInput.test.ts
+++ b/tests/boundary/filesystem/cliJsonInput.test.ts
@@ -1,11 +1,20 @@
 import { execFile } from "node:child_process";
-import { chmod, symlink, writeFile } from "node:fs/promises";
+import { constants as bufferConstants } from "node:buffer";
+import {
+  chmod,
+  open,
+  symlink,
+  type FileHandle,
+  writeFile,
+} from "node:fs/promises";
 import { join } from "node:path";
 import { promisify } from "node:util";
 
 import { describe, expect, it, onTestFinished } from "vitest";
 
+import { isCliOperationFailure } from "../../../src/cliLogging.js";
 import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
+import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js";
 import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
 
@@ -85,6 +94,51 @@ describe("CLI JSON file selection", () => {
 });
 
 describe("CLI JSON input", () => {
+  it("reports a valid file beyond the runtime string limit as too large", async () => {
+    const root = await createTestTempDirectory("rea-json-input-too-large-");
+    const path = join(root, "input.json");
+    const size = bufferConstants.MAX_STRING_LENGTH + 1;
+    await writeValidOversizedObject(path, size);
+
+    const result = await parseCliJsonInput(path, "test-input");
+    if (result.ok) throw new Error("Expected oversized JSON to be rejected");
+    expect(analysisCliErrorEnvelopeSchema.parse(result.error)).toEqual(
+      result.error,
+    );
+    expect(result).toMatchObject({
+      ok: false,
+      error: {
+        code: "resource_constraint",
+        input_path: path,
+        input_reason: "too-large",
+        details: {
+          resource: "memory",
+          reported_limits: {
+            boundary: "cli-json-input",
+            max_string_code_units: bufferConstants.MAX_STRING_LENGTH,
+          },
+        },
+        remediation: {
+          action:
+            "Split the JSON into smaller inputs or rerun its producer on a smaller subset, then retry.",
+        },
+      },
+    });
+
+    expect(isCliOperationFailure(result.error)).toBe(true);
+
+    const characterCount =
+      Math.floor(bufferConstants.MAX_STRING_LENGTH / 2) + 2;
+    await writeValidMultibyteString(path, characterCount);
+
+    const multibyteResult = await parseCliJsonInput(path, "test-input");
+    if (!multibyteResult.ok)
+      throw new Error("Expected large multibyte JSON to fit the string limit");
+    if (typeof multibyteResult.value !== "string")
+      throw new Error("Expected parsed JSON string");
+    expect(multibyteResult.value.length).toBe(characterCount);
+  }, 20_000);
+
   it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => {
     expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
       ok: false,
@@ -177,3 +231,47 @@ describe("CLI JSON input", () => {
     },
   );
 });
+
+const writeRepeatedBytes = async (
+  handle: FileHandle,
+  bytes: Buffer,
+  length: number,
+): Promise => {
+  let remaining = length;
+  while (remaining > 0) {
+    const chunkLength = Math.min(bytes.length, remaining);
+    await handle.writeFile(bytes.subarray(0, chunkLength));
+    remaining -= chunkLength;
+  }
+};
+
+const writeValidOversizedObject = async (
+  path: string,
+  size: number,
+): Promise => {
+  const handle = await open(path, "w");
+  const whitespace = Buffer.alloc(1024 * 1024, 0x20);
+  try {
+    await handle.writeFile("{");
+    await writeRepeatedBytes(handle, whitespace, size - 2);
+    await handle.writeFile("}");
+  } finally {
+    await handle.close();
+  }
+};
+
+const writeValidMultibyteString = async (
+  path: string,
+  characterCount: number,
+): Promise => {
+  const encodedCharacters = Buffer.from("é".repeat(512 * 1024));
+  const byteLength = characterCount * 2 + 2;
+  const handle = await open(path, "w");
+  try {
+    await handle.writeFile('"');
+    await writeRepeatedBytes(handle, encodedCharacters, byteLength - 2);
+    await handle.writeFile('"');
+  } finally {
+    await handle.close();
+  }
+};

From f0dc233d64de4c215c453c346e516b7622713e95 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:59:09 +0800
Subject: [PATCH 058/189] fix(setup): recognize supported Nobara hosts

---
 docs/installation.md                 | 2 +-
 docs/user-visible-errors.csv         | 4 ++--
 src/application/Doctor.test.ts       | 2 +-
 src/application/DoctorDiagnostics.ts | 2 +-
 src/application/LinuxHopper.test.ts  | 3 +++
 src/application/LinuxHopper.ts       | 3 ++-
 6 files changed, 10 insertions(+), 6 deletions(-)

diff --git a/docs/installation.md b/docs/installation.md
index 89fcbba45..ad141737b 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -290,7 +290,7 @@ vendor-defined limits, and a paid license is optional. REA reuses any detected
 installation and preserves Hopper during uninstall.
 
 The supported native host baseline is macOS 12+, Ubuntu 24.04+, Fedora 41+,
-64-bit Arch Linux, or CachyOS. Ghidra and IDA have their own provider-specific
+Nobara 44+, 64-bit Arch Linux, or CachyOS. Ghidra and IDA have their own provider-specific
 host requirements; Windows Ghidra uses the [experimental P0 boundary](windows-ghidra-p0.md).
 
 On macOS, approved setup downloads the official DMG, checks its published size
diff --git a/docs/user-visible-errors.csv b/docs/user-visible-errors.csv
index 1adbcbbbc..a1c3536f3 100644
--- a/docs/user-visible-errors.csv
+++ b/docs/user-visible-errors.csv
@@ -56,7 +56,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
 46,src/application/Uninstall.ts:removeManagedPath symlink,Managed cache/state/skill path is a symbolic link,Refused to follow symlink {path}.,Exposes local path and does not explain manual safety check,"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",implemented,focused assertion passed
 47,src/application/Uninstall.ts:removeManagedPath failure,Managed item removal fails,{path} could not be removed.,Exposes local path and gives no recovery,"This item could not be removed. Check file permissions, then rerun uninstall.",implemented,verified by injected managed-path removal failure test
 48,src/application/DoctorDiagnostics.ts:node,Runtime version is outside supported ranges,"Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.",Low risk; exact dependency recovery,Keep current copy,unchanged,verified by doctor unit test
-49,src/application/Doctor.ts:host,Host OS/distribution is unsupported,"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS.",Low risk; clearly states supported choices,Keep current copy,unchanged,verified by doctor unit tests
+49,src/application/Doctor.ts:host,Host OS/distribution is unsupported,"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, and CachyOS.",Low risk; clearly states supported choices,Keep current copy,unchanged,verified by doctor unit tests
 50,src/application/Doctor.ts:analysis engine,Optional deep-analysis executable cannot be found,"Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",Low risk in setup-specific diagnostic; exact recovery paths,Keep current copy,unchanged,verified by doctor unit tests
 51,src/application/Doctor.ts:target,Optional target path fails shared validation,Supply a readable local app or program path.,Low risk; tells caller valid target class,Keep current copy,unchanged,verified by doctor unit test
 52,src/application/Setup.ts:approval,Setup plan lacks approval,"Review the setup plan, then rerun interactively or with --yes.",Low risk; exact authorization recovery,Keep current copy,unchanged,verified by setup unit tests
@@ -67,7 +67,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
 57,src/application/Setup.ts:unsupported platform,Platform is neither macOS nor Linux,REA supports Hopper on macOS and selected 64-bit Linux distributions.,Low risk; states support boundary,Keep current copy,unchanged,verified by setup unit test
 58,src/application/SetupHost.ts:unsupported Node,Runtime version cannot run setup,"Install Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ and rerun setup.",Low risk; exact dependency and retry,Keep current copy,unchanged,verified by setup host tests
 59,src/application/Setup.ts:unsupported macOS,macOS version is missing or older than 12,Upgrade to macOS 12 or newer.,Low risk; exact support floor,Keep current copy,unchanged,verified by setup host tests
-60,src/application/Setup.ts:unsupported Linux,Linux distribution is outside supported set,"REA supports Hopper on Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS.",Low risk; exact supported alternatives,Keep current copy,unchanged,verified by setup unit test
+60,src/application/Setup.ts:unsupported Linux,Linux distribution is outside supported set,"REA supports Hopper on Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, and CachyOS.",Low risk; exact supported alternatives,Keep current copy,unchanged,verified by setup unit test
 61,src/application/process/ProcessCli.ts:readJson read,Process scenario or evidence file cannot be read,Raw filesystem exception through CLI framework,Can expose local paths/codes and no recovery,"Process input file could not be read. Check that the path exists and is readable.",implemented,verified by focused CLI test
 62,src/application/process/ProcessCli.ts:readJson size,Process scenario or evidence file exceeds 64 MiB,Process JSON input exceeds byte limit,Does not state limit or recovery,"Process input file is too large. Reduce it below 64 MiB, then try again.",implemented,verified by focused sparse-file CLI test
 63,src/application/process/ProcessCli.ts:readJson parse,Process scenario or evidence file is malformed JSON,Raw JSON parser exception through CLI framework,Can expose parser implementation and lacks recovery,"Process input file is not valid JSON. Repair the file, then try again.",implemented,verified by focused CLI test
diff --git a/src/application/Doctor.test.ts b/src/application/Doctor.test.ts
index 5c8dbc10e..70b85bf6a 100644
--- a/src/application/Doctor.test.ts
+++ b/src/application/Doctor.test.ts
@@ -22,7 +22,7 @@ describe("doctor", () => {
       ),
     ).toEqual({
       node: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
-      host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
+      host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
       hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
       target: "Supply a readable local app or program path.",
     });
diff --git a/src/application/DoctorDiagnostics.ts b/src/application/DoctorDiagnostics.ts
index 106d89845..39d838fde 100644
--- a/src/application/DoctorDiagnostics.ts
+++ b/src/application/DoctorDiagnostics.ts
@@ -113,7 +113,7 @@ const hostCheck = async (host: DoctorHost): Promise => {
       : `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`);
   return check("host", supported, detail, {
     remediation:
-      "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
+      "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
     classification: "unsupported_host",
   });
 };
diff --git a/src/application/LinuxHopper.test.ts b/src/application/LinuxHopper.test.ts
index be115cc71..4e622da6c 100644
--- a/src/application/LinuxHopper.test.ts
+++ b/src/application/LinuxHopper.test.ts
@@ -58,6 +58,7 @@ describe("Linux Hopper host classification", () => {
   it.each([
     ['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
     ["ID=fedora\nVERSION_ID=41\n", "rpm"],
+    ['ID=nobara\nVERSION_ID="44"\nID_LIKE="rhel centos fedora"\n', "rpm"],
     ["ID=arch\n", "arch"],
     ["ID=cachyos\nID_LIKE=arch\n", "arch"],
   ] as const)("accepts an official Hopper distribution", (document, family) => {
@@ -88,6 +89,8 @@ describe("Linux Hopper host classification", () => {
   it.each([
     'ID=ubuntu\nVERSION_ID="22.04"\n',
     "ID=fedora\nVERSION_ID=40\n",
+    'ID=nobara\nVERSION_ID="43"\nID_LIKE="rhel centos fedora"\n',
+    'ID=derivative\nVERSION_ID="44"\nID_LIKE="rhel centos fedora"\n',
     'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
     "ID=manjaro\nID_LIKE=arch\n",
     "ID=garuda\nID_LIKE=arch\n",
diff --git a/src/application/LinuxHopper.ts b/src/application/LinuxHopper.ts
index f090ba7cf..8a934f559 100644
--- a/src/application/LinuxHopper.ts
+++ b/src/application/LinuxHopper.ts
@@ -152,7 +152,8 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
     (id === "arch" ||
       id === "cachyos" ||
       (id === "ubuntu" && versionAtLeast(versionId, 24)) ||
-      (id === "fedora" && versionAtLeast(versionId, 41)));
+      (id === "fedora" && versionAtLeast(versionId, 41)) ||
+      (id === "nobara" && versionAtLeast(versionId, 44)));
   const identity = {
     id,
     ...(versionId === undefined ? {} : { versionId }),

From 7915ee51781878ed67e094259924b6e6f3093b3f Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:00:08 +0800
Subject: [PATCH 059/189] feat(javascript): record Electron integrity
 mismatches

---
 docs/javascript-artifact-reconstruction.md    |  15 +-
 docs/mcp-contracts.md                         |   6 +
 .../JavaScriptApplicationEvidence.ts          |   1 +
 .../JavaScriptApplicationService.ts           |   1 +
 .../JavaScriptArtifactGraphBuilder.ts         |  11 ++
 .../JavaScriptArtifactReconstruction.ts       |   8 +-
 .../JavaScriptArtifactReconstructionInput.ts  |   1 +
 .../javascript/JavaScriptArtifactFiles.ts     |  77 +++++---
 src/cli/coreBinaryCommands.ts                 |  11 +-
 src/cli/electronCommands.ts                   |   7 +-
 src/cliObservationOptions.ts                  |   4 +
 .../javascript/electronToolContracts.ts       |   3 +-
 .../javascriptExportShapeComparisonExample.ts |   2 +
 .../javascriptRuntimeReconciliationExample.ts |   1 +
 src/domain/analysisErrorPresentation.ts       |   9 +-
 src/domain/artifactGraph.ts                   |   2 +-
 .../javascriptApplicationAnalysis.ts          |   3 +
 .../cli/javascriptIntegrityPolicyCli.test.ts  |  48 +++++
 .../javascriptIntegrityPolicy.test.ts         | 168 ++++++++++++++++++
 tests/boundary/mcp/electronMcp.test.ts        |  48 +++++
 tests/fixtures/strippedAsarAddon.ts           |  38 ++++
 21 files changed, 429 insertions(+), 35 deletions(-)
 create mode 100644 tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts
 create mode 100644 tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
 create mode 100644 tests/fixtures/strippedAsarAddon.ts

diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md
index 39b003844..372934b7a 100644
--- a/docs/javascript-artifact-reconstruction.md
+++ b/docs/javascript-artifact-reconstruction.md
@@ -22,7 +22,7 @@ The tool reads the caller-selected local directory or ASAR path directly:
 ```bash
 rea analyze /absolute/path/to/apps/app.asar --json
 rea analyze-javascript-application /absolute/path/to/apps/app.asar \
-  --json
+  --integrity-policy record-and-continue --json
 ```
 
 Generic `rea analyze` selects this static provider for directories and `.asar`
@@ -47,11 +47,14 @@ The equivalent MCP input is:
 ```json
 {
   "input_path": "/absolute/path/to/apps/app.asar",
-  "format": "auto"
+  "format": "auto",
+  "integrity_policy": "fail"
 }
 ```
 
 `input_path` must be absolute. `format` accepts `auto`, `asar`, or `directory`.
+`integrity_policy` accepts `fail` or `record-and-continue`; both CLI routes and
+the MCP tool default to `fail`.
 The result retains the canonical local path, root artifact digest, artifact
 manifest and graph commitments, JavaScript Application Graph, static
 Electron summary, reconstruction statistics, and explicit limitations. It does
@@ -63,8 +66,12 @@ ASAR inventory checks Electron integrity metadata for embedded archive entries
 and supplied `.asar.unpacked` companion files. An integrity failure identifies
 the logical path, declared and calculated SHA-256 values, and whether the entry
 was unpacked. By default, a mismatch is returned as a failure with its artifact
-context. Requests that support `integrity_policy` can explicitly select
-`record-and-continue` to inspect verified siblings while retaining the mismatch.
+context. Application analysis can explicitly select `record-and-continue` to
+analyze observed bytes while retaining each contradiction's declared and
+observed hashes and `observed-untrusted` trust. Such results mark application
+graph coverage partial and include every contradicted path in the limitations.
+Mismatched nested ASARs stay opaque rather than being expanded. An unpacked
+entry whose companion bytes were not supplied remains `unavailable`.
 
 An unpacked entry whose companion bytes were not supplied remains
 `unavailable`. REA continues analyzing embedded JavaScript and records the
diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md
index d1e95d1b8..f25ea8a57 100644
--- a/docs/mcp-contracts.md
+++ b/docs/mcp-contracts.md
@@ -339,3 +339,9 @@ Contradictory bytes are quarantined from nested expansion and recorded with
 declared and observed hashes, trust, provenance, path, and unpacked state.
 Verified siblings continue. Comparisons classify the result as a contradiction
 and reconstruction cannot treat it as unchanged.
+
+`analyze_javascript_application` accepts the same policy in MCP and as
+`--integrity-policy` on both JavaScript CLI routes. Its result returns the
+canonical `integrity_contradictions` records and marks application graph
+coverage partial when any mismatch is continued. Contradicted nested ASARs
+remain opaque.
diff --git a/src/application/javascript/JavaScriptApplicationEvidence.ts b/src/application/javascript/JavaScriptApplicationEvidence.ts
index 34753c127..d3e3862d3 100644
--- a/src/application/javascript/JavaScriptApplicationEvidence.ts
+++ b/src/application/javascript/JavaScriptApplicationEvidence.ts
@@ -90,4 +90,5 @@ const parameters = (
   input: AnalyzeJavaScriptApplicationInput,
 ): EvidenceObservation["parameters"] => ({
   format: input.format,
+  integrity_policy: input.integrity_policy,
 });
diff --git a/src/application/javascript/JavaScriptApplicationService.ts b/src/application/javascript/JavaScriptApplicationService.ts
index 28f6691ee..995356698 100644
--- a/src/application/javascript/JavaScriptApplicationService.ts
+++ b/src/application/javascript/JavaScriptApplicationService.ts
@@ -60,6 +60,7 @@ export const analyzeJavaScriptApplicationValidated = async (
       {
         input_path: input.input_path,
         format: input.format,
+        integrity_policy: input.integrity_policy,
       },
       options.signal,
       options.progress,
diff --git a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
index 0c39ce458..29648aa44 100644
--- a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
@@ -140,6 +140,13 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
       null,
     );
   if (unknownGap) return partialApplicationCoverage([], null);
+  if (context.snapshot.integrity_contradictions.length > 0) {
+    const nestedArchiveWasOpaque =
+      context.snapshot.integrity_contradictions.some(({ logical_path }) =>
+        logical_path.toLowerCase().endsWith(".asar"),
+      );
+    return partialApplicationCoverage([], nestedArchiveWasOpaque ? null : 0);
+  }
   return completeApplicationCoverage();
 };
 
@@ -178,6 +185,10 @@ const graphLimitations = (
   );
   return [
     ...context.analysis.limitations,
+    ...context.snapshot.integrity_contradictions.map(
+      ({ logical_path: path }) =>
+        `Artifact integrity metadata contradicts observed bytes at ${path}; the observed bytes are untrusted.`,
+    ),
     ...selfReferenceOmissions(
       relationshipOmissions.selfImports,
       ["import specifier", "import specifiers"],
diff --git a/src/application/javascript/JavaScriptArtifactReconstruction.ts b/src/application/javascript/JavaScriptArtifactReconstruction.ts
index 692321d8c..39ff299f3 100644
--- a/src/application/javascript/JavaScriptArtifactReconstruction.ts
+++ b/src/application/javascript/JavaScriptArtifactReconstruction.ts
@@ -11,6 +11,7 @@ import { createJavaScriptArtifactReader as createReader } from "../../artifacts/
 import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
 import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticGraph.js";
 import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
+import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
 import { analyzeAndProjectJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
 import { readJavaScriptArtifactFiles } from "../../artifacts/javascript/JavaScriptArtifactFiles.js";
 import { buildImmutableJavaScriptArtifactGraphSteps } from "./JavaScriptArtifactGraphBuilder.js";
@@ -34,6 +35,7 @@ export interface JavaScriptArtifactReconstructionResult {
   readonly root_artifact_sha256: string;
   readonly inventory_manifest_id: string;
   readonly inventory_graph_sha256: string;
+  readonly integrity_contradictions: ArtifactInventorySnapshot["integrity_contradictions"];
   readonly graph: JavaScriptApplicationGraph;
   readonly semantic_graph: JavaScriptSemanticGraph;
   readonly electron_summary: ElectronBoundarySummary;
@@ -66,7 +68,10 @@ export const reconstructJavaScriptArtifact = async (
   abortIfNeeded(signal);
   const path = await resolveSelectedInput(input.input_path);
   const format = await resolveFormat(path, input);
-  const snapshot = await scanCanonicalArtifactInventory(path, { signal });
+  const snapshot = await scanCanonicalArtifactInventory(path, {
+    signal,
+    integrity: { mode: input.integrity_policy },
+  });
   if (snapshot.manifest.root_format !== format)
     throw new ArtifactReaderFailure(
       "format",
@@ -141,6 +146,7 @@ export const reconstructJavaScriptArtifact = async (
       root_artifact_sha256: snapshot.manifest.root_sha256,
       inventory_manifest_id: snapshot.manifest.manifest_id,
       inventory_graph_sha256: snapshot.manifest.graph_sha256,
+      integrity_contradictions: snapshot.integrity_contradictions,
       graph,
       semantic_graph: semanticGraph,
       electron_summary: summarizeElectronBoundaries(analysis),
diff --git a/src/application/javascript/JavaScriptArtifactReconstructionInput.ts b/src/application/javascript/JavaScriptArtifactReconstructionInput.ts
index 3bdb9b639..f2988ee2b 100644
--- a/src/application/javascript/JavaScriptArtifactReconstructionInput.ts
+++ b/src/application/javascript/JavaScriptArtifactReconstructionInput.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
 export const javascriptArtifactReconstructionInputSchema = z.strictObject({
   input_path: z.string().min(1),
   format: z.enum(["auto", "asar", "directory"]).default("auto"),
+  integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
 });
 
 /** Parsed local reconstruction request. */
diff --git a/src/artifacts/javascript/JavaScriptArtifactFiles.ts b/src/artifacts/javascript/JavaScriptArtifactFiles.ts
index a726fd88a..a6aa2600f 100644
--- a/src/artifacts/javascript/JavaScriptArtifactFiles.ts
+++ b/src/artifacts/javascript/JavaScriptArtifactFiles.ts
@@ -15,6 +15,7 @@ import {
 } from "../ArtifactReader.js";
 import { streamChunkToBuffer } from "../StreamBytes.js";
 import { hashReadable } from "../ArtifactHash.js";
+import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
 import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
 
 import type {
@@ -32,9 +33,14 @@ interface ExpectedFile {
   readonly kind: JavaScriptArtifactFileKind;
 }
 
+interface ExpectedContainer {
+  readonly hash_status: ArtifactOccurrence["hash_status"];
+  readonly inventory: JavaScriptArtifactContainer | null;
+}
+
 interface ReadContext {
   readonly expected: ReadonlyMap;
-  readonly expectedContainers: ReadonlyMap;
+  readonly expectedContainers: ReadonlyMap;
   readonly registry: ArtifactPathRegistry;
   readonly files: JavaScriptArtifactFile[];
   readonly containers: JavaScriptArtifactContainer[];
@@ -136,7 +142,32 @@ const visitReader = async (
       const nestedAsar = isFilesystemAsar(entry, path);
       context.registry.add(path, nestedAsar ? "directory" : entry.kind);
       if (nestedAsar) {
-        const inventory = expectedContainer(path, context);
+        const container = context.expectedContainers.get(path);
+        // Inventory deliberately does not expand unverified or unavailable
+        // nested archives. Keep the same boundary here when reconstruction
+        // reads the active entries again.
+        if (container === undefined)
+          throw new ArtifactReaderFailure(
+            "integrity",
+            `Nested ASAR was not present in inventory: ${path}`,
+          );
+        if (container.hash_status === "mismatched") continue;
+        if (container.hash_status === "unavailable")
+          throw new ArtifactReaderFailure(
+            "unavailable",
+            `Nested ASAR bytes were unavailable during inventory: ${path}`,
+          );
+        if (container.hash_status !== "verified")
+          throw new ArtifactReaderFailure(
+            "integrity",
+            `Nested ASAR was not integrity-verified: ${path}`,
+          );
+        const inventory = container.inventory;
+        if (inventory === null)
+          throw new ArtifactReaderFailure(
+            "integrity",
+            `Verified nested ASAR has no inventory node: ${path}`,
+          );
         await verifyEntryBytes(
           await frame.reader.open(entry, context.signal),
           inventory,
@@ -183,19 +214,6 @@ const visitReader = async (
   }
 };
 
-const expectedContainer = (
-  path: string,
-  context: ReadContext,
-): JavaScriptArtifactContainer => {
-  const container = context.expectedContainers.get(path);
-  if (container === undefined)
-    throw new ArtifactReaderFailure(
-      "integrity",
-      `Nested ASAR disappeared from inventory: ${path}`,
-    );
-  return container;
-};
-
 const readText = async (
   context: ReadContext,
   input: ReadTextInput,
@@ -259,14 +277,24 @@ const expectedInventory = (
   snapshot: ArtifactInventorySnapshot,
 ): {
   readonly files: ReadonlyMap;
-  readonly containers: ReadonlyMap;
+  readonly containers: ReadonlyMap;
 } => {
   const nodes = new Map(snapshot.nodes.map((node) => [node.artifact_id, node]));
   const files = new Map();
-  const containers = new Map();
+  const containers = new Map();
   for (const occurrence of snapshot.occurrences) {
-    if (occurrence.artifact_id === null || occurrence.logical_path === ".")
+    if (occurrence.logical_path === ".") continue;
+    const isNestedAsar =
+      occurrence.entry_kind === "file" &&
+      occurrence.logical_path.toLowerCase().endsWith(".asar");
+    if (occurrence.artifact_id === null) {
+      if (isNestedAsar)
+        containers.set(occurrence.logical_path, {
+          hash_status: occurrence.hash_status,
+          inventory: null,
+        });
       continue;
+    }
     const node = nodes.get(occurrence.artifact_id);
     if (node === undefined)
       throw new ArtifactReaderFailure(
@@ -277,12 +305,15 @@ const expectedInventory = (
     // Suffixes only describe file candidates; a directory such as
     // node_modules/@zip.js remains a graph node and must never be opened.
     if (occurrence.entry_kind !== "file") continue;
-    if (occurrence.logical_path.toLowerCase().endsWith(".asar"))
+    if (isNestedAsar)
       containers.set(occurrence.logical_path, {
-        path: occurrence.logical_path,
-        sha256: node.sha256,
-        bytes: node.size,
-        inventory_artifact_id: node.artifact_id,
+        hash_status: occurrence.hash_status,
+        inventory: {
+          path: occurrence.logical_path,
+          sha256: node.sha256,
+          bytes: node.size,
+          inventory_artifact_id: node.artifact_id,
+        },
       });
     const kind = relevantKind(occurrence.logical_path);
     if (kind === undefined) continue;
diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts
index d3623141b..5130b8634 100644
--- a/src/cli/coreBinaryCommands.ts
+++ b/src/cli/coreBinaryCommands.ts
@@ -16,6 +16,7 @@ import type { CliInstance } from "./types.js";
 import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
 import { withCommandCancellation } from "./commandCancellation.js";
 import type { CliResultOutput } from "./streamedJsonOutput.js";
+import { javascriptApplicationOptions } from "../cliObservationOptions.js";
 
 /** Register provider-neutral binary overview and procedure CLI commands. */
 export const registerCoreBinaryCommands = (
@@ -53,7 +54,10 @@ const registerOverviewCommands = (
     args: z.object({
       path: z.string().describe("App, program, or analysis database path"),
     }),
-    options: overviewOptions,
+    options: overviewOptions.extend({
+      integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy,
+    }),
+    alias: { integrityPolicy: "integrity-policy" },
     run: async ({ args, options, format }) => {
       const output =
         resultOutput === undefined
@@ -66,7 +70,10 @@ const registerOverviewCommands = (
         return withCommandCancellation((signal) =>
           logCliCommand(logger, "analyze", () =>
             runCliJavaScriptApplicationAnalysis(
-              { input_path: resolve(args.path) },
+              {
+                input_path: resolve(args.path),
+                integrity_policy: options.integrityPolicy,
+              },
               output,
               signal,
             ),
diff --git a/src/cli/electronCommands.ts b/src/cli/electronCommands.ts
index 6b11183d7..79dcd7cc1 100644
--- a/src/cli/electronCommands.ts
+++ b/src/cli/electronCommands.ts
@@ -193,11 +193,16 @@ const registerJavaScriptApplicationCommand = (
       path: z.string().describe("ASAR or extracted application path"),
     }),
     options: javascriptApplicationOptions,
+    alias: { integrityPolicy: "integrity-policy" },
     run: ({ args, options, format }) =>
       withCommandCancellation((signal) =>
         logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () =>
           runCliJavaScriptApplicationAnalysis(
-            { input_path: args.path, format: options.artifactFormat },
+            {
+              input_path: args.path,
+              format: options.artifactFormat,
+              integrity_policy: options.integrityPolicy,
+            },
             resultOutput === undefined
               ? undefined
               : {
diff --git a/src/cliObservationOptions.ts b/src/cliObservationOptions.ts
index 1131e94dd..cdb1b1f0e 100644
--- a/src/cliObservationOptions.ts
+++ b/src/cliObservationOptions.ts
@@ -63,4 +63,8 @@ export const javascriptApplicationOptions = z.object({
     .enum(["auto", "asar", "directory"])
     .default("auto")
     .describe("Application artifact format"),
+  integrityPolicy: z
+    .enum(["fail", "record-and-continue"])
+    .default("fail")
+    .describe("Behavior when declared application integrity does not match"),
 });
diff --git a/src/contracts/javascript/electronToolContracts.ts b/src/contracts/javascript/electronToolContracts.ts
index e35e134b5..659ea99f0 100644
--- a/src/contracts/javascript/electronToolContracts.ts
+++ b/src/contracts/javascript/electronToolContracts.ts
@@ -79,7 +79,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
     name: "analyze_javascript_application",
     ...toolContractMetadata("analyze_javascript_application"),
     description:
-      "Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns all recovered graph nodes, edges, semantic relations, limitations, and coverage.",
+      "Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns recovered graph nodes, edges, semantic relations, integrity contradictions, limitations, and coverage. Integrity mismatches fail by default; record-and-continue retains observed bytes as untrusted and marks graph coverage partial.",
     kind: "electron-provider",
     inputSchema: analyzeJavaScriptApplicationInputSchema,
     outputSchema: applicationOutputSchema,
@@ -89,6 +89,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
         input: {
           input_path: "/Applications/Example.app/Contents/Resources/app.asar",
           format: "auto",
+          integrity_policy: "fail",
         },
       },
     ],
diff --git a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
index 69deff0ac..2fb7b96cc 100644
--- a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
+++ b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
@@ -28,6 +28,7 @@ const captures = {
       "agm_f30ded9a83d43a3980417bbe63dfad569e83386f243c4d6a01af0166372cb9e6",
     inventory_graph_sha256:
       "4b8aceaf67e43fd8317ec1f5fd1df5235f8fa402335accf011683e008c6bc62c",
+    integrity_contradictions: [],
   },
   total: {
     input_path: "/examples/javascript-export-presence/right",
@@ -37,6 +38,7 @@ const captures = {
       "agm_d3ceaa1af38fb3474070ca25c0d4644282e5fb7d5824cee3e3a81391481e9fc1",
     inventory_graph_sha256:
       "3e9bc926951480c35385efe5650d9d781631bd74c37a523d543b5fbe06b01ce6",
+    integrity_contradictions: [],
   },
 };
 const summary = {
diff --git a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
index 127e13799..bd3991dd6 100644
--- a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
+++ b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
@@ -128,6 +128,7 @@ export const JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE = createEvidence(
       root_artifact_sha256: applicationSha256,
       inventory_manifest_id: `agm_${"2".repeat(64)}`,
       inventory_graph_sha256: "3".repeat(64),
+      integrity_contradictions: [],
       graph,
       semantic_graph: semanticGraph,
       summary: {
diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts
index 93ffeb4fb..7c71a9b5d 100644
--- a/src/domain/analysisErrorPresentation.ts
+++ b/src/domain/analysisErrorPresentation.ts
@@ -191,7 +191,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
   const standardMessage = standardErrorMessage(error._tag);
   if (standardMessage !== undefined) return standardMessage;
   if (error instanceof ArtifactOperationError)
-    return artifactMessage(error.reason);
+    return artifactMessage(error.operation, error.reason);
   if (error instanceof EvidenceReferenceError)
     return error.reason === "missing"
       ? `Evidence ${error.evidenceId} is not retained in this session. Supply complete inline Evidence, re-run its producer, or import its bundle before using this reference.`
@@ -326,7 +326,10 @@ const START_FAILURE_TAGS: ReadonlySet = new Set([
   "HopperStartError",
 ]);
 
-const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
+const artifactMessage = (
+  operation: ArtifactOperationError["operation"],
+  reason: ArtifactOperationError["reason"],
+): string => {
   if (reason === "cancelled")
     return "Artifact operation was cancelled. Start it again when ready.";
   if (reason === "limit")
@@ -335,6 +338,8 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
     return "Artifact contains an unsafe or conflicting internal path. Inspect the reported path and correct the artifact before retrying.";
   if (reason === "unavailable")
     return "Artifact processing is unavailable for the current target or host. Check artifact support and required tools.";
+  if (reason === "integrity" && operation === "analyze_javascript_application")
+    return "Artifact bytes contradict declared integrity. If expected, rerun analyze_javascript_application with integrity_policy=record-and-continue (CLI: --integrity-policy record-and-continue) to retain observed bytes as untrusted; otherwise get a fresh copy.";
   if (reason === "format" || reason === "integrity")
     return "Artifact is invalid or has changed. Get a fresh copy and try again.";
   return "Artifact could not be read or written. Check file access and try again.";
diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts
index 721c007df..34e4af932 100644
--- a/src/domain/artifactGraph.ts
+++ b/src/domain/artifactGraph.ts
@@ -137,7 +137,7 @@ const artifactOccurrenceSchema = z.object({
 });
 
 /** Observed bytes that contradict a container's declared integrity identity. */
-const integrityContradictionSchema = z.object({
+export const integrityContradictionSchema = z.object({
   contradiction_id: contradictionIdSchema,
   occurrence_id: occurrenceIdSchema,
   parent_artifact_id: artifactIdSchema,
diff --git a/src/domain/javascript/javascriptApplicationAnalysis.ts b/src/domain/javascript/javascriptApplicationAnalysis.ts
index 313ab5291..8d976d7fb 100644
--- a/src/domain/javascript/javascriptApplicationAnalysis.ts
+++ b/src/domain/javascript/javascriptApplicationAnalysis.ts
@@ -12,6 +12,7 @@ import {
 } from "./javascriptSemanticGraph.js";
 import { digestSchema } from "../digests.js";
 import { prefixedDigestSchema } from "../digests.js";
+import { integrityContradictionSchema } from "../artifactGraph.js";
 import { localPathStringSchema } from "../localPath.js";
 
 const countSchema = z.number().int().min(0);
@@ -20,6 +21,7 @@ const countSchema = z.number().int().min(0);
 export const analyzeJavaScriptApplicationInputSchema = z.strictObject({
   input_path: localPathStringSchema,
   format: z.enum(["auto", "asar", "directory"]).default("auto"),
+  integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
 });
 
 /** Compact counts for the high-level Electron architecture/security surface. */
@@ -66,6 +68,7 @@ const applicationAnalysisResultShape = z.strictObject({
   root_artifact_sha256: digestSchema,
   inventory_manifest_id: prefixedDigestSchema("agm"),
   inventory_graph_sha256: digestSchema,
+  integrity_contradictions: z.array(integrityContradictionSchema),
   graph: javascriptApplicationGraphSchema,
   summary: electronBoundarySummarySchema,
   statistics: reconstructionStatisticsSchema,
diff --git a/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts b/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts
new file mode 100644
index 000000000..4883ac741
--- /dev/null
+++ b/tests/boundary/cli/javascriptIntegrityPolicyCli.test.ts
@@ -0,0 +1,48 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+import { expect, it } from "vitest";
+
+import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
+
+const execute = promisify(execFile);
+const run = async (arguments_: readonly string[]): Promise => {
+  const { stdout } = await execute(
+    process.execPath,
+    ["scripts/rea.mjs", ...arguments_, "--json"],
+    { cwd: process.cwd(), maxBuffer: 16 * 1024 * 1024 },
+  );
+  return JSON.parse(stdout);
+};
+
+it.each(["analyze-javascript-application", "analyze"])(
+  "%s carries the integrity policy into shared JavaScript analysis",
+  async (command) => {
+    const { archive, addon } = await createStrippedAsarAddon();
+    const result = await run([
+      command,
+      archive,
+      "--integrity-policy",
+      "record-and-continue",
+    ]);
+    expect(result).toMatchObject({
+      operation: "analyze_javascript_application",
+      parameters: { integrity_policy: "record-and-continue" },
+      normalized_result: {
+        integrity_contradictions: [
+          { logical_path: addon, trust: "observed-untrusted" },
+        ],
+        graph: { coverage: { status: "partial" } },
+      },
+    });
+  },
+);
+
+it("rejects the JavaScript integrity policy on binary-only inspection", async () => {
+  await expect(
+    run(["inspect", "unused.asar", "--integrityPolicy", "record-and-continue"]),
+  ).rejects.toMatchObject({
+    code: 1,
+    stdout: expect.stringContaining("Unknown flag: --integrityPolicy"),
+  });
+});
diff --git a/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
new file mode 100644
index 000000000..7291d888e
--- /dev/null
+++ b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
@@ -0,0 +1,168 @@
+import { createHash } from "node:crypto";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { createPackage, createPackageWithOptions } from "@electron/asar";
+import { expect, it } from "vitest";
+
+import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
+import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
+import { createJavaScriptArtifactReader } from "../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
+import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
+import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
+import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+it("records an explicitly continued Electron addon mismatch as untrusted evidence", async () => {
+  const { archive, addon, original, stripped } =
+    await createStrippedAsarAddon();
+  const rejected = await analyzeJavaScriptApplication({ input_path: archive });
+  if (rejected.ok) throw new Error("Expected strict integrity failure");
+  expect(projectAnalysisError(rejected.error)).toMatchObject({
+    code: "artifact_integrity_mismatch",
+    details: {
+      logical_path: addon,
+      declared_sha256: expect.any(String),
+      calculated_sha256: expect.any(String),
+      unpacked: true,
+    },
+    remediation: {
+      action: expect.stringContaining("integrity_policy=record-and-continue"),
+    },
+  });
+
+  const continued = await analyzeJavaScriptApplication({
+    input_path: archive,
+    integrity_policy: "record-and-continue",
+  });
+  if (!continued.ok) throw new Error("Expected explicit continuation");
+  const result = javascriptApplicationAnalysisResultSchema.parse(
+    continued.value.normalized_result,
+  );
+  const contradiction = result.integrity_contradictions.find(
+    ({ logical_path }) => logical_path === addon,
+  );
+  expect(contradiction).toMatchObject({
+    logical_path: addon,
+    declared_sha256: createHash("sha256").update(original).digest("hex"),
+    observed_sha256: createHash("sha256").update(stripped).digest("hex"),
+    trust: "observed-untrusted",
+  });
+  expect(result.graph.coverage.status).toBe("partial");
+  expect(result.graph.coverage.omitted_count).toBe(0);
+  expect(result.graph.limitations).toContain(
+    `Artifact integrity metadata contradicts observed bytes at ${addon}; the observed bytes are untrusted.`,
+  );
+  expect(continued.value.parameters).toMatchObject({
+    format: "auto",
+    integrity_policy: "record-and-continue",
+  });
+  expect(result.statistics.parsed_javascript_files).toBeGreaterThan(0);
+  expect(JSON.stringify(result.graph)).toContain(
+    createHash("sha256").update(stripped).digest("hex"),
+  );
+});
+
+it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", async () => {
+  const root = await createTestTempDirectory("rea-mismatched-nested-asar-");
+  const nestedSource = join(root, "nested-source");
+  const outerSource = join(root, "outer-source");
+  const archive = join(root, "app.asar");
+  const nestedArchive = join(outerSource, "nested.asar");
+  const nestedSecret = "export const nestedOnly = 'not inventoried';\n";
+  await mkdir(nestedSource);
+  await mkdir(outerSource);
+  await writeFile(join(nestedSource, "main.js"), nestedSecret);
+  await writeFile(join(outerSource, "main.js"), "export const outer = true;\n");
+  await createPackage(nestedSource, nestedArchive);
+  await createPackageWithOptions(outerSource, archive, {
+    unpack: "nested.asar",
+  });
+  const unpackedNested = join(`${archive}.unpacked`, "nested.asar");
+  const nestedBytes = await readFile(unpackedNested);
+  nestedBytes[0] = (nestedBytes[0] ?? 0) ^ 0xff;
+  await writeFile(unpackedNested, nestedBytes);
+
+  const analyzed = await analyzeJavaScriptApplication({
+    input_path: archive,
+    integrity_policy: "record-and-continue",
+  });
+  if (!analyzed.ok) throw new Error("Expected explicit continuation");
+  const result = javascriptApplicationAnalysisResultSchema.parse(
+    analyzed.value.normalized_result,
+  );
+  expect(result.integrity_contradictions).toMatchObject([
+    { logical_path: "nested.asar", trust: "observed-untrusted" },
+  ]);
+  expect(result.statistics.nested_asar_containers).toBe(0);
+  expect(JSON.stringify(result)).not.toContain(nestedSecret);
+  expect(result.graph.coverage.status).toBe("partial");
+  expect(result.graph.coverage.omitted_count).toBeNull();
+});
+
+it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
+  const expression = Array.from(
+    { length: 20 },
+    () => '(true ? "a" : "b")',
+  ).join(" + ");
+  const declarations = ['const value0 = "x";'];
+  for (let index = 1; index <= 30; index += 1) {
+    const previous = `value${String(index - 1)}`;
+    declarations.push(
+      `const value${String(index)} = ${previous} + ${previous};`,
+    );
+  }
+  declarations.push("const answer = value30;");
+  const { archive } = await createStrippedAsarAddon([
+    { path: "app.js", contents: `const answer = { nested: ${expression} };` },
+    { path: "growth.js", contents: declarations.join("\n") },
+  ]);
+  const analyzed = await analyzeJavaScriptApplication({
+    input_path: archive,
+    integrity_policy: "record-and-continue",
+  });
+  if (!analyzed.ok) throw new Error("Expected explicit continuation");
+  const result = javascriptApplicationAnalysisResultSchema.parse(
+    analyzed.value.normalized_result,
+  );
+  expect(result.integrity_contradictions).toHaveLength(1);
+  expect(result.graph.coverage).toMatchObject({
+    status: "partial",
+    omitted_count: null,
+    limits: expect.arrayContaining([
+      expect.objectContaining({
+        name: "javascript_semantic_primitive_candidates",
+        unit: "items",
+      }),
+      expect.objectContaining({
+        name: "javascript_semantic_primitive_bytes",
+        unit: "bytes",
+      }),
+    ]),
+  });
+});
+
+it("rejects a nested ASAR introduced after inventory as artifact drift", async () => {
+  const root = await createTestTempDirectory("rea-new-nested-asar-");
+  const nestedSource = join(root, "nested-source");
+  await mkdir(nestedSource);
+  await writeFile(join(root, "main.js"), "export const outer = true;\n");
+  await writeFile(
+    join(nestedSource, "main.js"),
+    "export const nested = true;\n",
+  );
+  const snapshot = await scanCanonicalArtifactInventory(root, {});
+  await createPackage(nestedSource, join(root, "new.asar"));
+  const reader = createJavaScriptArtifactReader(root, "directory");
+  try {
+    await expect(
+      readJavaScriptArtifactFiles(reader, snapshot),
+    ).rejects.toMatchObject({
+      reason: "integrity",
+      message: "Nested ASAR was not present in inventory: new.asar",
+    });
+  } finally {
+    await reader.close();
+  }
+});
diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts
index 4910fd9f8..293a34a99 100644
--- a/tests/boundary/mcp/electronMcp.test.ts
+++ b/tests/boundary/mcp/electronMcp.test.ts
@@ -9,6 +9,7 @@ import { afterEach, expect, it } from "vitest";
 import { z } from "zod";
 
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
 
 import { createTestBinarySession } from "../../fixtures/binarySession.js";
 import type { ElectronActiveObservationPort } from "../../../src/application/javascript/ElectronActiveObservationPort.js";
@@ -22,6 +23,7 @@ import {
 } from "../../fixtures/fakeCdpBrowser.js";
 import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
 import { createElectronActiveObservationFixtureResult } from "../../../src/domain/javascript/electronActiveObservation.fixture.js";
+import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
 
 const browsers: FakeCdpBrowser[] = [];
 const resources: Array<{ close(): Promise }> = [];
@@ -37,6 +39,52 @@ afterEach(async () => {
   );
 });
 
+it("lets MCP JavaScript analysis continue only with recorded untrusted ASAR bytes", async () => {
+  const { archive, addon } = await createStrippedAsarAddon();
+  const session = createTestBinarySession(() => ({
+    execute: () => Promise.resolve(observed(null)),
+    close: () => Promise.resolve(resultOk(null)),
+  }));
+  const server = createServer({ kind: "session", session });
+  const client = new Client({ name: "asar-integrity-policy", version: "1" });
+  const [clientTransport, serverTransport] =
+    InMemoryTransport.createLinkedPair();
+  resources.push(client, server, session);
+  await server.connect(serverTransport);
+  await client.connect(clientTransport);
+
+  const rejected = await client.callTool({
+    name: "analyze_javascript_application",
+    arguments: { input_path: archive },
+  });
+  expect(parseMcpToolError(rejected)).toMatchObject({
+    error: {
+      code: "artifact_integrity_mismatch",
+      remediation: {
+        action: expect.stringContaining("integrity_policy=record-and-continue"),
+      },
+    },
+  });
+
+  const continued = await client.callTool({
+    name: "analyze_javascript_application",
+    arguments: {
+      input_path: archive,
+      integrity_policy: "record-and-continue",
+    },
+  });
+  expect(continued.isError).not.toBe(true);
+  expect(continued.structuredContent).toMatchObject({
+    parameters: { integrity_policy: "record-and-continue" },
+    normalized_result: {
+      integrity_contradictions: [
+        { logical_path: addon, trust: "observed-untrusted" },
+      ],
+      graph: { coverage: { status: "partial" } },
+    },
+  });
+});
+
 it("exposes endpoint-scoped Electron discovery and inspection as Evidence", async () => {
   const root = await createTestTempDirectory("rea-electron-mcp-");
   temporary.push(root);
diff --git a/tests/fixtures/strippedAsarAddon.ts b/tests/fixtures/strippedAsarAddon.ts
new file mode 100644
index 000000000..5ff76356c
--- /dev/null
+++ b/tests/fixtures/strippedAsarAddon.ts
@@ -0,0 +1,38 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+import { createPackageWithOptions } from "@electron/asar";
+
+import { createTestTempDirectory } from "./temporaryDirectory.js";
+
+interface AdditionalAsarFile {
+  readonly path: string;
+  readonly contents: string;
+}
+
+/** Create an Electron ASAR, then model a distro-stripped unpacked native addon. */
+export const createStrippedAsarAddon = async (
+  additionalFiles: readonly AdditionalAsarFile[] = [],
+) => {
+  const root = await createTestTempDirectory("rea-stripped-asar-addon-");
+  const source = join(root, "source");
+  const archive = join(root, "app.asar");
+  const addon = "node_modules/btime/binding.node";
+  const addonPath = join(source, "node_modules", "btime", "binding.node");
+  const original = Buffer.from("upstream native addon bytes");
+  const stripped = Buffer.from("stripped native addon");
+  await mkdir(join(source, "node_modules", "btime"), { recursive: true });
+  await writeFile(join(source, "main.js"), "module.exports = 'observed';\n");
+  await writeFile(addonPath, original);
+  for (const file of additionalFiles) {
+    const path = join(source, file.path);
+    await mkdir(dirname(path), { recursive: true });
+    await writeFile(path, file.contents);
+  }
+  await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
+  await writeFile(
+    join(`${archive}.unpacked`, "node_modules", "btime", "binding.node"),
+    stripped,
+  );
+  return { root, archive, addon, original, stripped };
+};

From ed8fcae94b699b62b44162f880faa077a36c455d Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:05:02 +0800
Subject: [PATCH 060/189] fix(javascript): store source map URLs once

---
 docs/javascript-application-graph.md          |   8 +
 .../JavaScriptArtifactGraphFindings.ts        |  70 ++++----
 .../javascriptSourceMapComments.test.ts       |  27 ++-
 .../javascriptSourceMapLocations.test.ts      | 169 +++++++++++++++---
 4 files changed, 212 insertions(+), 62 deletions(-)

diff --git a/docs/javascript-application-graph.md b/docs/javascript-application-graph.md
index bbe4093ad..fd87b00ee 100644
--- a/docs/javascript-application-graph.md
+++ b/docs/javascript-application-graph.md
@@ -73,6 +73,14 @@ The directed relation vocabulary is `contains`, `loads`, `imports`, `maps_to`,
 and `changed_from`. Provider names are deliberately absent from both
 vocabularies.
 
+For a `maps_to` edge targeting a source-map node, the edge carries
+`resolved_path` and `declared_url_sha256`. The target node's reference
+observation carries that same digest and the exact `declared_url`; match the
+digest to select the URL belonging to that edge when several references share
+one physical source map. The full URL is kept out of node identity, display
+label, and edge properties, so large inline data URLs are stored once per
+source-map reference.
+
 For example, a source-owned synthetic fixture proves this path without using a
 third-party application:
 
diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts
index edd9ea920..cff140220 100644
--- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts
@@ -1,3 +1,5 @@
+import { createHash } from "node:crypto";
+
 import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
 import type { JavaScriptStaticAnalysis } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
 import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -283,6 +285,9 @@ const addSourceMapEdge = (
   context: JavaScriptArtifactGraphContext,
   input: FindingInput,
 ): void => {
+  const declaredUrlSha256 = createHash("sha256")
+    .update(input.value.declared_url)
+    .digest("hex");
   const resolvedPath = resolveArtifactPathByContext({
     declaredPath: input.value.declared_url,
     sourcePath: input.file.path,
@@ -293,38 +298,43 @@ const addSourceMapEdge = (
     resolvedPath === null ? undefined : context.filesByPath.get(resolvedPath);
   const resolvedNode =
     resolvedPath === null ? undefined : context.fileNodes.get(resolvedPath);
-  const target =
-    resolvedFile?.kind === "source-map" && resolvedNode !== undefined
-      ? resolvedNode
-      : context.accumulator.addNode({
-          kind: "source-map",
-          identity: artifactLocalIdentity(
+  const isAvailable =
+    resolvedFile?.kind === "source-map" && resolvedNode !== undefined;
+  const target = context.accumulator.addNode({
+    kind: "source-map",
+    identity:
+      isAvailable && resolvedNode !== undefined
+        ? resolvedNode.identity
+        : artifactLocalIdentity(
             input.file.sha256,
             "unresolved-source-map",
-            input.value.declared_url,
+            declaredUrlSha256,
           ),
-          observations: [
-            {
-              label: input.value.declared_url,
-              properties: {
-                declared_url: input.value.declared_url,
-                resolved_path: resolvedPath,
-                available: false,
-              },
-              evidence: staticInferenceEvidence({
-                sha256: input.file.sha256,
-                path: input.file.path,
-                range: input.value.location,
-                operation: "discover-source-map",
-                coverage: input.coverage,
-                confidence: "medium",
-                limitations: [
-                  "The declared source map was not present in the inventoried artifact.",
-                ],
-              }),
-            },
-          ],
-        });
+    observations: [
+      {
+        label: "source map reference",
+        properties: {
+          declared_url: input.value.declared_url,
+          declared_url_sha256: declaredUrlSha256,
+          resolved_path: resolvedPath,
+          available: isAvailable,
+        },
+        evidence: staticInferenceEvidence({
+          sha256: input.file.sha256,
+          path: input.file.path,
+          range: input.value.location,
+          operation: "discover-source-map",
+          coverage: input.coverage,
+          confidence: "medium",
+          limitations: isAvailable
+            ? []
+            : [
+                "The declared source map was not present in the inventoried artifact.",
+              ],
+        }),
+      },
+    ],
+  });
   addStaticInferenceEdge(context, {
     source: input.asset,
     target,
@@ -333,7 +343,7 @@ const addSourceMapEdge = (
     coverage: input.coverage,
     relation: "maps_to",
     properties: {
-      declared_url: input.value.declared_url,
+      declared_url_sha256: declaredUrlSha256,
       resolved_path: resolvedPath,
     },
   });
diff --git a/tests/boundary/filesystem/javascriptSourceMapComments.test.ts b/tests/boundary/filesystem/javascriptSourceMapComments.test.ts
index 46625dde2..aaaae82f4 100644
--- a/tests/boundary/filesystem/javascriptSourceMapComments.test.ts
+++ b/tests/boundary/filesystem/javascriptSourceMapComments.test.ts
@@ -20,8 +20,12 @@ it("creates source-map graph relationships only for real comments", async () =>
   ).toEqual([]);
   expect(
     withoutDirective.graph.edges.filter(
-      ({ relation, properties }) =>
-        relation === "maps_to" && properties.declared_url !== undefined,
+      ({ relation, target_node_id }) =>
+        relation === "maps_to" &&
+        withoutDirective.graph.nodes.some(
+          ({ kind, node_id }) =>
+            kind === "source-map" && node_id === target_node_id,
+        ),
     ),
   ).toEqual([]);
 
@@ -32,12 +36,17 @@ it("creates source-map graph relationships only for real comments", async () =>
   expect(
     withDirective.graph.nodes.filter(({ kind }) => kind === "source-map"),
   ).toHaveLength(1);
+  const nodes = new Map(
+    withDirective.graph.nodes.map((node) => [node.node_id, node]),
+  );
+  const sourceMapEdge = withDirective.graph.edges.find(
+    ({ relation, target_node_id }) =>
+      relation === "maps_to" &&
+      nodes.get(target_node_id)?.kind === "source-map",
+  );
   expect(
-    withDirective.graph.edges
-      .filter(
-        ({ relation, properties }) =>
-          relation === "maps_to" && properties.declared_url !== undefined,
-      )
-      .map(({ properties }) => properties.declared_url),
-  ).toEqual(["real.map"]);
+    nodes
+      .get(sourceMapEdge?.target_node_id ?? "")
+      ?.observations.map(({ properties }) => properties.declared_url),
+  ).toContain("real.map");
 });
diff --git a/tests/boundary/filesystem/javascriptSourceMapLocations.test.ts b/tests/boundary/filesystem/javascriptSourceMapLocations.test.ts
index e8be59a4b..278324b54 100644
--- a/tests/boundary/filesystem/javascriptSourceMapLocations.test.ts
+++ b/tests/boundary/filesystem/javascriptSourceMapLocations.test.ts
@@ -6,6 +6,10 @@ import { expect, it } from "vitest";
 
 import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import {
+  parseJavaScriptApplicationGraph,
+  serializeJavaScriptApplicationGraph,
+} from "../../../src/domain/javascript/javascriptApplicationGraph.js";
 
 it.each(["\n", "\r\n", "\r", "\u2028", "\u2029"])(
   "preserves source-map graph evidence coordinates after %j",
@@ -16,33 +20,139 @@ it.each(["\n", "\r\n", "\r", "\u2028", "\u2029"])(
     await writeFile(join(root, "app.js"), source);
     const result = await reconstructJavaScriptArtifact({ input_path: root });
     expect(result.statistics.parse_failures).toBe(0);
-    const edges = result.graph.edges.filter(
-      ({ relation, properties }) =>
-        relation === "maps_to" && properties.declared_url === "app.js.map",
+    const nodes = new Map(
+      result.graph.nodes.map((node) => [node.node_id, node]),
     );
-    expect(edges).toHaveLength(1);
-    expect(edges[0]?.evidence).toMatchObject({
-      state: "inferred",
-      artifact: {
-        sha256: createHash("sha256").update(source).digest("hex"),
+    const edge = result.graph.edges.find(
+      ({ relation, target_node_id }) =>
+        relation === "maps_to" &&
+        nodes.get(target_node_id)?.kind === "source-map",
+    );
+    expect(edge).toMatchObject({
+      properties: {
+        declared_url_sha256: createHash("sha256")
+          .update("app.js.map")
+          .digest("hex"),
+        resolved_path: null,
       },
-      location: {
-        available: true,
-        value: {
-          kind: "source-range",
-          source: "app.js",
-          start: { line: 2, column: 2 },
-          end: { line: 2, column: directive.length + 2 },
+      evidence: {
+        state: "inferred",
+        artifact: {
+          sha256: createHash("sha256").update(source).digest("hex"),
+        },
+        location: {
+          available: true,
+          value: {
+            kind: "source-range",
+            source: "app.js",
+            start: { line: 2, column: 2 },
+            end: { line: 2, column: directive.length + 2 },
+          },
         },
       },
     });
-    expect(edges[0]?.properties).toMatchObject({
-      declared_url: "app.js.map",
-      resolved_path: null,
-    });
+    expect(
+      nodes
+        .get(edge?.target_node_id ?? "")
+        ?.observations.some(
+          ({ properties }) => properties.declared_url === "app.js.map",
+        ),
+    ).toBe(true);
   },
 );
 
+it("owns an inline source-map URL once and recovers it from the target after JSON roundtrip", async () => {
+  const root = await createTestTempDirectory("rea-inline-source-map-url-");
+  const sourceContent = "source;".repeat(16_384);
+  const sourceMap = JSON.stringify({
+    version: 3,
+    sources: ["src/app.js"],
+    sourcesContent: [sourceContent],
+    names: [],
+    mappings: "AAAA",
+  });
+  const declaredUrl = `data:application/json;base64,${Buffer.from(sourceMap).toString("base64")}`;
+  await writeFile(
+    join(root, "app.js"),
+    `const app = true;\n//# sourceMappingURL=${declaredUrl}\n`,
+  );
+
+  const result = await reconstructJavaScriptArtifact({ input_path: root });
+  const serialized = serializeJavaScriptApplicationGraph(result.graph);
+  const graph = parseJavaScriptApplicationGraph(JSON.parse(serialized));
+  const edge = graph.edges.find(
+    ({ relation, target_node_id }) =>
+      relation === "maps_to" &&
+      graph.nodes.some(
+        ({ kind, node_id }) =>
+          kind === "source-map" && node_id === target_node_id,
+      ),
+  );
+  const target = graph.nodes.find(
+    ({ node_id }) => node_id === edge?.target_node_id,
+  );
+
+  const edgeUrlSha256 = edge?.properties.declared_url_sha256;
+  const observation = target?.observations.find(
+    ({ properties }) => properties.declared_url_sha256 === edgeUrlSha256,
+  );
+  expect(edgeUrlSha256).toBe(
+    createHash("sha256").update(declaredUrl).digest("hex"),
+  );
+  expect(observation?.properties.declared_url).toBe(declaredUrl);
+  expect(observation?.properties).toMatchObject({
+    resolved_path: null,
+    available: false,
+  });
+  expect(serialized.split(declaredUrl)).toHaveLength(2);
+});
+
+it("associates each source-map URL with its edge when aliases share one physical map", async () => {
+  const root = await createTestTempDirectory("rea-source-map-aliases-");
+  await mkdir(join(root, "dist"));
+  await writeFile(
+    join(root, "dist", "app.js.map"),
+    JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }),
+  );
+  await writeFile(
+    join(root, "dist", "one.js"),
+    "//# sourceMappingURL=app.js.map\n",
+  );
+  await writeFile(
+    join(root, "dist", "two.js"),
+    "//# sourceMappingURL=./app.js.map\n",
+  );
+
+  const result = await reconstructJavaScriptArtifact({ input_path: root });
+  const serialized = serializeJavaScriptApplicationGraph(result.graph);
+  const graph = parseJavaScriptApplicationGraph(JSON.parse(serialized));
+  const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
+  const mapEdges = graph.edges.filter(
+    ({ relation, target_node_id }) =>
+      relation === "maps_to" &&
+      nodes.get(target_node_id)?.kind === "source-map",
+  );
+  expect(mapEdges).toHaveLength(2);
+  expect(mapEdges[0]?.target_node_id).toBe(mapEdges[1]?.target_node_id);
+  expect(
+    mapEdges.map((edge) => {
+      const target = nodes.get(edge.target_node_id);
+      const observation = target?.observations.find(
+        ({ properties }) =>
+          properties.declared_url_sha256 ===
+          edge.properties.declared_url_sha256,
+      );
+      return {
+        declared_url: observation?.properties.declared_url,
+        resolved_path: edge.properties.resolved_path,
+      };
+    }),
+  ).toEqual([
+    { declared_url: "app.js.map", resolved_path: "dist/app.js.map" },
+    { declared_url: "./app.js.map", resolved_path: "dist/app.js.map" },
+  ]);
+});
+
 it("resolves a bare source-map file name and worker URL next to the script", async () => {
   const root = await createTestTempDirectory("rea-source-map-relative-");
   await mkdir(join(root, "dist"));
@@ -72,13 +182,26 @@ it("resolves a bare source-map file name and worker URL next to the script", asy
   const result = await reconstructJavaScriptArtifact({ input_path: root });
   const nodes = new Map(result.graph.nodes.map((node) => [node.node_id, node]));
   const mapEdge = result.graph.edges.find(
-    ({ relation, properties }) =>
-      relation === "maps_to" && properties.declared_url === "app.js.map",
+    ({ relation, target_node_id }) =>
+      relation === "maps_to" &&
+      nodes.get(target_node_id)?.kind === "source-map",
   );
-  expect(mapEdge?.properties).toMatchObject({
-    declared_url: "app.js.map",
+  expect(mapEdge?.properties).toEqual({
+    declared_url_sha256: createHash("sha256")
+      .update("app.js.map")
+      .digest("hex"),
     resolved_path: "dist/app.js.map",
   });
+  expect(
+    nodes
+      .get(mapEdge?.target_node_id ?? "")
+      ?.observations.some(
+        ({ properties }) =>
+          properties.declared_url === "app.js.map" &&
+          properties.resolved_path === "dist/app.js.map" &&
+          properties.available === true,
+      ),
+  ).toBe(true);
   expect(nodes.get(mapEdge?.target_node_id ?? "")?.identity.strategy).toBe(
     "content-digest",
   );

From b4a19193fe3baf9075f8ac419517021ea0c71ea3 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 01:59:12 +0800
Subject: [PATCH 061/189] fix(setup): install the skill for Claude Code

---
 docs/installation.md                          |  12 +-
 src/application/Doctor.fixture.ts             |   1 -
 src/application/Doctor.test.ts                |   1 -
 src/application/Doctor.ts                     |  73 +++-----
 src/application/Setup.fixture.ts              |   2 +-
 src/application/Setup.planning.test.ts        |  40 +++++
 src/application/Setup.recovery.test.ts        |   4 +-
 src/application/Setup.ts                      |  31 +++-
 src/application/SetupHost.ts                  |  18 +-
 src/application/SetupPlan.ts                  |  50 +++---
 src/application/SetupSkill.ts                 | 136 +++++++++++---
 src/application/SetupTypes.ts                 |   7 +-
 src/application/Uninstall.ts                  |  49 ++++-
 .../filesystem/clientLifecycle.test.ts        |  39 +++-
 tests/boundary/filesystem/setupSkill.test.ts  | 169 +++++++++++++++---
 15 files changed, 484 insertions(+), 148 deletions(-)

diff --git a/docs/installation.md b/docs/installation.md
index ad141737b..fecbe4aa0 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -192,6 +192,13 @@ default. Hopper is a separate optional choice: setup shows its proposed
 installation or connection and requires its own explicit approval. It can also
 save verified paths for an existing Ghidra installation.
 
+The bundled skill is installed where each selected client discovers personal
+skills: Claude Code uses `~/.claude/skills` (or
+`$CLAUDE_CONFIG_DIR/skills` when configured), while other supported clients
+use the shared `~/.agents/skills` directory. A mixed selection plans both
+paths. Selecting the skill without a client uses the shared directory. Setup
+leaves existing skill copies in other locations untouched.
+
 After selection, review the plan's exact paths and changes and approve before
 REA writes files or installs Hopper. You can cancel at any prompt.
 
@@ -199,7 +206,7 @@ Before applying changes, REA checks your current configuration. The plan lists:
 
 - an existing Hopper installation, a verified existing Ghidra installation, or the official Hopper package it proposes to install;
 - each detected agent configuration path;
-- the REA skill destination;
+- each selected REA skill destination;
 - external software, network origins, integrity evidence, and package-manager
   commands.
 
@@ -658,7 +665,8 @@ and other MCP servers. Purging removes only REA's cache and state under
 `~/.rea`. A client configuration that is malformed, unreadable, or at an unsafe
 path stops the operation before anything is removed, and a client that fails
 while being updated stops the remaining removals. A purge path that is a
-symbolic link is retained and reported rather than followed. See the
+symbolic link is retained and reported rather than followed. Uninstall checks
+REA's managed shared and Claude Code personal skill locations. See the
 [CLI guide](cli.md#output-and-exit-status) for exit statuses.
 
 ## MCP Registry
diff --git a/src/application/Doctor.fixture.ts b/src/application/Doctor.fixture.ts
index 375439098..770b78fe6 100644
--- a/src/application/Doctor.fixture.ts
+++ b/src/application/Doctor.fixture.ts
@@ -27,7 +27,6 @@ export const createDoctorHostFixture = (
     Promise.resolve({
       version: PRODUCT_IDENTITY.skillVersion,
       toolCount: CATALOG_IDENTITY.counts.mcp_tools,
-      catalogDigest: null,
       canonical: true,
     }),
   ...overrides,
diff --git a/src/application/Doctor.test.ts b/src/application/Doctor.test.ts
index 70b85bf6a..afc0b5ef1 100644
--- a/src/application/Doctor.test.ts
+++ b/src/application/Doctor.test.ts
@@ -176,7 +176,6 @@ describe("doctor installation identity", () => {
           Promise.resolve({
             version: "10",
             toolCount: null,
-            catalogDigest: null,
             canonical: false,
           }),
       }),
diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts
index 5426a6453..88dfda4c8 100644
--- a/src/application/Doctor.ts
+++ b/src/application/Doctor.ts
@@ -1,5 +1,5 @@
 import { constants } from "node:fs";
-import { access, readFile, readdir } from "node:fs/promises";
+import { access, readdir } from "node:fs/promises";
 import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
 import { join } from "node:path";
 
@@ -15,7 +15,11 @@ import {
   readLinuxDistribution,
   type LinuxDistribution,
 } from "./LinuxHopper.js";
-import { canonicalSkillNeedsInstall } from "./SetupSkill.js";
+import {
+  claudeCodeSkillsDirectory,
+  readInstalledSkillIdentity,
+  type InstalledSkillIdentity,
+} from "./SetupSkill.js";
 import { CATALOG_IDENTITY } from "../catalogIdentity.js";
 import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
 import {
@@ -92,20 +96,13 @@ export interface DoctorHost {
   manualHopperPaths(): Promise;
   providerInspections?(): Promise;
   installationPaths?(): Promise;
-  installedSkillIdentity?(): Promise;
+  installedSkillIdentity?(
+    clientIds: readonly string[],
+  ): Promise;
   clientRegistrations?(): Promise;
   ilspyCmdVersion?(path: string): Promise;
 }
 
-/** Observed skill metadata and comparison with the packaged instruction bundle. */
-interface InstalledSkillIdentity {
-  readonly version: string | null;
-  readonly toolCount: number | null;
-  readonly catalogDigest: string | null;
-  /** Whether all managed instruction and reference files match this package. */
-  readonly canonical: boolean;
-}
-
 /** Structured result returned by the read-only doctor workflow. */
 export interface DoctorReport {
   readonly healthy: boolean;
@@ -143,8 +140,6 @@ interface DoctorIdentity {
   readonly skill: {
     readonly installed_version: string | null;
     readonly installed_tool_count: number | null;
-    /** Legacy catalog digest observed in older bundles; current bundles omit it. */
-    readonly installed_catalog_digest: string | null;
     readonly state: "aligned" | "stale" | "missing";
     readonly remediation: string | null;
   };
@@ -161,12 +156,13 @@ export const runDoctor = async (
   host: DoctorHost = systemDoctorHost(),
   requestedScope?: DoctorScope,
 ): Promise => {
+  const scope = normalizeDoctorScope(requestedScope, target);
   const {
     checks: diagnosticChecks,
     hopperPath,
     providerInspections,
   } = await collectDoctorDiagnostics(target, host);
-  const identity = await collectDoctorIdentity(host);
+  const identity = await collectDoctorIdentity(host, scope);
   const checks = [...diagnosticChecks, ...identity.checks];
   const providers = {
     hopperAvailable:
@@ -178,7 +174,6 @@ export const runDoctor = async (
     providerInspections,
   };
   const environmentHealthy = doctorHealthy(checks, providers);
-  const scope = normalizeDoctorScope(requestedScope, target);
   const scoped = scopeDoctorChecks({
     checks,
     registrations: identity.value.registrations,
@@ -202,14 +197,20 @@ export const runDoctor = async (
 
 const collectDoctorIdentity = async (
   host: DoctorHost,
+  scope: DoctorScopeReport,
 ): Promise<{
   readonly checks: readonly DoctorCheck[];
   readonly value: DoctorIdentity;
 }> => {
   const installationPaths = (await host.installationPaths?.()) ?? [];
-  const installedSkillIdentity = await host.installedSkillIdentity?.();
-  const skillAligned = skillIdentityAligned(installedSkillIdentity);
   const registrations = (await host.clientRegistrations?.()) ?? [];
+  const skillClientIds =
+    scope.mode === "audit-wide"
+      ? registrations.map(({ client }) => client)
+      : scope.clients;
+  const installedSkillIdentity =
+    await host.installedSkillIdentity?.(skillClientIds);
+  const skillAligned = skillIdentityAligned(installedSkillIdentity);
   return {
     checks: [
       ...(skillAligned ? [] : [skillIdentityCheck(installedSkillIdentity)]),
@@ -237,7 +238,6 @@ const collectDoctorIdentity = async (
       skill: {
         installed_version: installedSkillIdentity?.version ?? null,
         installed_tool_count: installedSkillIdentity?.toolCount ?? null,
-        installed_catalog_digest: installedSkillIdentity?.catalogDigest ?? null,
         state:
           installedSkillIdentity === undefined
             ? "missing"
@@ -437,7 +437,12 @@ export const systemDoctorHost = (
         return [];
       }
     },
-    installedSkillIdentity: () => installedSkillIdentity(homeDirectory),
+    installedSkillIdentity: (clientIds) =>
+      readInstalledSkillIdentity(
+        homeDirectory,
+        clientIds,
+        claudeCodeSkillsDirectory(homeDirectory, environment),
+      ),
     clientRegistrations: () =>
       readClientRegistrationStatuses(homeDirectory, undefined, {
         platform,
@@ -502,34 +507,6 @@ const manualHopperPaths = async (home: string): Promise => {
   return paths;
 };
 
-const readInstalledSkill = (home: string): Promise =>
-  readFile(
-    join(home, ".agents/skills", PRODUCT_IDENTITY.skillName, "SKILL.md"),
-    "utf8",
-  );
-
-const installedSkillIdentity = async (
-  home: string,
-): Promise => {
-  try {
-    const content = await readInstalledSkill(home);
-    const countText = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
-    return {
-      canonical: !(await canonicalSkillNeedsInstall(home)),
-      version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
-      toolCount:
-        countText === undefined ? null : Number.parseInt(countText, 10),
-      catalogDigest:
-        /^\s{2}catalog_digest:\s*"([a-f0-9]{64})"\s*$/mu.exec(content)?.[1] ??
-        null,
-    };
-  } catch (cause: unknown) {
-    // best-effort cleanup: optional skill probing; failure means unknown.
-    void cause;
-    return undefined;
-  }
-};
-
 const uniqueLines = (value: string): string[] => [
   ...new Set(
     value
diff --git a/src/application/Setup.fixture.ts b/src/application/Setup.fixture.ts
index 078239e40..b15b7940e 100644
--- a/src/application/Setup.fixture.ts
+++ b/src/application/Setup.fixture.ts
@@ -18,6 +18,7 @@ import { setupRegistrationCommand } from "./SetupHost.js";
 export class FakeSetupHost implements SetupHost {
   readonly platform: NodeJS.Platform;
   readonly homeDirectory = "/fixture/home";
+  readonly claudeCodeSkillsDirectory = "/fixture/home/.claude/skills";
   readonly registrationCommand: readonly string[];
   nodeVersion = "24.18.0";
   version: string | undefined = "14.5";
@@ -186,7 +187,6 @@ export class FakeSetupHost implements SetupHost {
         skill: {
           installed_version: null,
           installed_tool_count: null,
-          installed_catalog_digest: null,
           state: this.skill === "unchanged" ? "aligned" : "missing",
           remediation: null,
         },
diff --git a/src/application/Setup.planning.test.ts b/src/application/Setup.planning.test.ts
index 41b2a7178..d1ca6baea 100644
--- a/src/application/Setup.planning.test.ts
+++ b/src/application/Setup.planning.test.ts
@@ -4,6 +4,46 @@ import { runSetup } from "./Setup.js";
 import type { SetupProgressEvent } from "./SetupTypes.js";
 import { FakeSetupHost, options } from "./Setup.fixture.js";
 
+describe("skill plan destinations", () => {
+  it("plans a Claude-only skill in its personal location", async () => {
+    const host = new FakeSetupHost();
+    host.clients = [{ name: "claude_code", configPath: "/claude.json" }];
+
+    const result = await runSetup(
+      { ...options(false), clientIds: ["claude_code"] },
+      host,
+    );
+
+    expect(
+      result.plannedActions
+        .filter(({ kind }) => kind === "install_skill")
+        .map(({ target }) => target),
+    ).toEqual(["/fixture/home/.claude/skills/reverse-engineer-anything"]);
+  });
+
+  it("plans both shared and personal skill roots for mixed clients", async () => {
+    const host = new FakeSetupHost();
+    host.clients = [
+      { name: "claude_code", configPath: "/claude.json" },
+      { name: "codex", configPath: "/codex.toml", format: "toml" },
+    ];
+
+    const result = await runSetup(
+      { ...options(false), clientIds: ["claude_code", "codex"] },
+      host,
+    );
+
+    expect(
+      result.plannedActions
+        .filter(({ kind }) => kind === "install_skill")
+        .map(({ target }) => target),
+    ).toEqual([
+      "/fixture/home/.agents/skills/reverse-engineer-anything",
+      "/fixture/home/.claude/skills/reverse-engineer-anything",
+    ]);
+  });
+});
+
 describe("setup workflow", () => {
   it("returns a complete plan without mutation", async () => {
     const host = new FakeSetupHost();
diff --git a/src/application/Setup.recovery.test.ts b/src/application/Setup.recovery.test.ts
index 57765ec23..95a479400 100644
--- a/src/application/Setup.recovery.test.ts
+++ b/src/application/Setup.recovery.test.ts
@@ -60,7 +60,7 @@ describe("setup workflow", () => {
     );
     expect(result.status).toBe("needs_human");
     expect(result.remediation).toBe(
-      "REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
+      "REA analysis skill could not be installed or verified. Check permissions for its planned skill directories, then rerun setup.",
     );
   });
 
@@ -194,7 +194,7 @@ describe("setup scoped readiness", () => {
     expect(result.status).toBe("needs_human");
     expect(host.hopperInstalls).toBe(0);
     expect(result.remediation).toBe(
-      "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.",
+      "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.",
     );
   });
 
diff --git a/src/application/Setup.ts b/src/application/Setup.ts
index 2d6a0ac90..ea99de6c7 100644
--- a/src/application/Setup.ts
+++ b/src/application/Setup.ts
@@ -67,20 +67,31 @@ export const runSetup = async (
     : (options.clientIds ??
       options.readinessScope?.clients ??
       discovery.defaultClientIds);
+  let skillNeedsInstall = await host.skillNeedsInstall(selectedClientIds);
   let skillSelected =
     options.installSkill === true ||
     (options.installSkill !== false && selectedClientIds.length > 0);
-  let installSkill = skillSelected && discovery.skillNeedsInstall;
+  let installSkill = skillSelected && skillNeedsInstall;
   let planDiscovery = discovery;
   if (interactiveSelection) {
+    const selectionSkillClientIds = [
+      ...new Set([
+        ...discovery.defaultClientIds,
+        ...discovery.detectedClientIds,
+      ]),
+    ];
+    const selectionSkillNeedsInstall = await host.skillNeedsInstall(
+      selectionSkillClientIds,
+    );
     const offerSkillAction =
-      options.installSkill !== false && discovery.skillNeedsInstall;
+      options.installSkill !== false && selectionSkillNeedsInstall;
     const selectionActions = await planSetupActions({
       discovery,
       host,
       providerEnvironment,
       command: host.registrationCommand,
       clientIds: [],
+      skillClientIds: selectionSkillClientIds,
       installSkill: offerSkillAction,
     });
     const decision = await confirm(selectionActions.plannedActions, {
@@ -111,6 +122,7 @@ export const runSetup = async (
     selectedClientIds = [...selectedActionIds]
       .filter((id) => id.startsWith("configure_client:"))
       .map((id) => id.slice("configure_client:".length));
+    skillNeedsInstall = await host.skillNeedsInstall(selectedClientIds);
     const proposedInstallAction = selectionActions.plannedActions.some(
       ({ id }) => id === "install_hopper",
     );
@@ -125,7 +137,7 @@ export const runSetup = async (
       (selectedActionIds.has("install_skill") &&
         selectedClientIds.length === 0) ||
       (options.installSkill !== false && selectedClientIds.length > 0);
-    installSkill = skillSelected && discovery.skillNeedsInstall;
+    installSkill = skillSelected && skillNeedsInstall;
   }
   const planned = await planSetupActions({
     discovery: planDiscovery,
@@ -133,6 +145,7 @@ export const runSetup = async (
     providerEnvironment,
     command: host.registrationCommand,
     clientIds: selectedClientIds,
+    skillClientIds: selectedClientIds,
     installSkill,
   });
   plannedActions = planned.plannedActions;
@@ -239,10 +252,15 @@ export const runSetup = async (
   if (clientFailure !== undefined) return fail(clientFailure);
   if (
     planSelection.installSkill &&
-    !(await installSkillAction(host, options, appliedActions))
+    !(await installSkillAction(
+      host,
+      options,
+      appliedActions,
+      selectedClientIds,
+    ))
   )
     return fail(
-      "REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
+      "REA analysis skill could not be installed or verified. Check permissions for its planned skill directories, then rerun setup.",
     );
   const doctor = summarizeDoctor(await host.doctor(readinessScope));
   const remediation = combineRemediation(
@@ -330,6 +348,7 @@ const installSkillAction = async (
   host: SetupHost,
   options: SetupOptions,
   appliedActions: string[],
+  skillClientIds: readonly string[],
 ): Promise => {
   const label = "REA reverse-engineering skill";
   emitProgress(options, {
@@ -337,7 +356,7 @@ const installSkillAction = async (
     label,
     state: "started",
   });
-  const skill = await host.installSkill();
+  const skill = await host.installSkill(skillClientIds);
   if (skill === "failed") {
     emitProgress(options, {
       actionId: "install_skill",
diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts
index 3e2d64e1a..068b8c012 100644
--- a/src/application/SetupHost.ts
+++ b/src/application/SetupHost.ts
@@ -16,6 +16,7 @@ import {
 import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js";
 import { supportedClients, type SetupClient } from "./SupportedClients.js";
 import {
+  claudeCodeSkillsDirectory as resolveClaudeCodeSkillsDirectory,
   canonicalSkillNeedsInstall,
   installCanonicalSkill,
 } from "./SetupSkill.js";
@@ -78,7 +79,7 @@ export const hostRemediation = async (
       : undefined;
   }
   if ((await host.linuxDistribution())?.supported === true) return undefined;
-  return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.";
+  return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.";
 };
 
 /** Production setup effects for Hopper, agent configuration, and the canonical skill directory. */
@@ -89,9 +90,14 @@ export const systemSetupHost = (
   const doctorHost = selectedDoctorHost ?? systemDoctorHost({ environment });
   const platform = doctorHost.platform;
   const { homeDirectory } = doctorHost;
+  const claudeSkillsDirectory = resolveClaudeCodeSkillsDirectory(
+    homeDirectory,
+    environment,
+  );
   return {
     platform,
     homeDirectory,
+    claudeCodeSkillsDirectory: claudeSkillsDirectory,
     registrationCommand: setupRegistrationCommand(
       platform,
       environment.npm_command === "exec",
@@ -143,8 +149,14 @@ export const systemSetupHost = (
             (aligned) => !aligned,
           ),
     inspectClientConfiguration: inspectClientConfiguration,
-    skillNeedsInstall: () => canonicalSkillNeedsInstall(homeDirectory),
-    installSkill: () => installCanonicalSkill(homeDirectory),
+    skillNeedsInstall: (clientIds) =>
+      canonicalSkillNeedsInstall(
+        homeDirectory,
+        clientIds,
+        claudeSkillsDirectory,
+      ),
+    installSkill: (clientIds) =>
+      installCanonicalSkill(homeDirectory, clientIds, claudeSkillsDirectory),
     doctor: (scope) => runDoctor(undefined, doctorHost, scope),
   };
 };
diff --git a/src/application/SetupPlan.ts b/src/application/SetupPlan.ts
index 87b741309..fc0d978a3 100644
--- a/src/application/SetupPlan.ts
+++ b/src/application/SetupPlan.ts
@@ -1,11 +1,11 @@
 import { join } from "node:path";
 
-import { PRODUCT_IDENTITY } from "../identity.js";
 import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
 import {
   linuxHopperInstallDisclosure,
   type LinuxPackageFamily,
 } from "./LinuxHopper.js";
+import { skillDestinations } from "./SetupSkill.js";
 import { macHopperInstallDisclosure } from "./MacHopper.js";
 import type {
   SetupAction,
@@ -20,7 +20,6 @@ import type { DoctorReport } from "./Doctor.js";
 export interface SetupDiscovery {
   readonly initialDoctor: Awaited>;
   readonly installHopper: boolean;
-  readonly skillNeedsInstall: boolean;
   readonly clients: readonly SetupClient[];
   readonly detectedClientIds: readonly string[];
   readonly defaultClientIds: readonly string[];
@@ -57,10 +56,9 @@ export const discoverSetupState = async (input: {
       input.proposeHopper &&
       (Object.keys(input.providerEnvironment).length === 0 ||
         linuxHopperRepairNeeded));
-  const [clients, detectedClients, skillNeedsInstall] = await Promise.all([
+  const [clients, detectedClients] = await Promise.all([
     input.host.supportedClients(),
     input.host.detectedClients(),
-    input.host.skillNeedsInstall(),
   ]);
   const detectedIds = new Set(detectedClients.map(({ name }) => name));
   const registrations = initialDoctor.identity?.registrations ?? [];
@@ -100,7 +98,6 @@ export const discoverSetupState = async (input: {
   return {
     initialDoctor,
     installHopper,
-    skillNeedsInstall,
     clients,
     detectedClientIds: [...detectedIds],
     defaultClientIds,
@@ -118,6 +115,7 @@ export const planSetupActions = async (input: {
   readonly providerEnvironment: SetupProviderEnvironment;
   readonly command: readonly string[];
   readonly clientIds: readonly string[];
+  readonly skillClientIds: readonly string[];
   readonly installSkill: boolean;
 }): Promise<{
   readonly plannedActions: readonly SetupAction[];
@@ -189,6 +187,8 @@ export const planSetupActions = async (input: {
       homeDirectory: input.host.homeDirectory,
       installHopper: input.discovery.installHopper,
       installSkill: input.installSkill,
+      skillClientIds: input.skillClientIds,
+      claudeCodeSkillsDirectory: input.host.claudeCodeSkillsDirectory,
       clients: clientPlans,
       providerEnvironment: input.providerEnvironment,
       ...(input.discovery.linuxPackageFamily === undefined
@@ -209,6 +209,8 @@ const setupPlan = (input: {
   readonly homeDirectory: string;
   readonly installHopper: boolean;
   readonly installSkill: boolean;
+  readonly skillClientIds: readonly string[];
+  readonly claudeCodeSkillsDirectory: string;
   readonly clients: readonly {
     readonly client: SetupClient;
     readonly operation: "create" | "update";
@@ -266,22 +268,28 @@ const setupPlan = (input: {
       ...(backupPath === undefined ? {} : { backupPath }),
     })),
   ...(input.installSkill
-    ? [
-        {
-          id: "install_skill",
-          kind: "install_skill" as const,
-          label: "REA reverse-engineering skill",
-          target: join(
-            input.homeDirectory,
-            ".agents/skills",
-            PRODUCT_IDENTITY.skillName,
-          ),
-          detail:
-            "Install or update the bundled REA reverse-engineering skill and on-demand references.",
-          external: false,
-          operation: "install" as const,
-        },
-      ]
+    ? skillDestinations(
+        input.homeDirectory,
+        input.skillClientIds,
+        input.claudeCodeSkillsDirectory,
+      ).map(({ client, path }): SetupAction => ({
+        id:
+          client === "claude_code"
+            ? "install_skill:claude_code"
+            : "install_skill",
+        kind: "install_skill",
+        label:
+          client === "claude_code"
+            ? "REA skill for Claude Code"
+            : "REA reverse-engineering skill",
+        target: path,
+        detail:
+          client === "claude_code"
+            ? "Install or update the REA skill in Claude Code's personal skill directory."
+            : "Install or update the bundled REA reverse-engineering skill and on-demand references.",
+        external: false,
+        operation: "install",
+      }))
     : []),
 ];
 
diff --git a/src/application/SetupSkill.ts b/src/application/SetupSkill.ts
index 346a1ace7..19a306f9a 100644
--- a/src/application/SetupSkill.ts
+++ b/src/application/SetupSkill.ts
@@ -19,8 +19,57 @@ interface CanonicalSkillFile {
   readonly original: string | undefined;
 }
 
-const skillRoot = (home: string): string =>
-  join(home, ".agents/skills", PRODUCT_IDENTITY.skillName);
+/** Managed skill location selected for a client family. */
+export interface SkillDestination {
+  readonly client: "shared" | "claude_code";
+  readonly path: string;
+}
+
+/** Metadata and byte alignment observed in selected skill installations. */
+export interface InstalledSkillIdentity {
+  readonly version: string | null;
+  readonly toolCount: number | null;
+  readonly canonical: boolean;
+}
+
+/** Resolve Claude Code personal skills from the selected environment. */
+export const claudeCodeSkillsDirectory = (
+  home: string,
+  environment: { readonly CLAUDE_CONFIG_DIR?: string } = {},
+): string =>
+  join(environment.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "skills");
+
+/** Resolve the skill roots required by a client selection, or all owned roots. */
+export const skillDestinations = (
+  home: string,
+  clientIds: readonly string[] | undefined,
+  claudeSkillsDirectory = claudeCodeSkillsDirectory(home),
+): readonly SkillDestination[] => {
+  const includeClaude =
+    clientIds === undefined || clientIds.includes("claude_code");
+  const includeShared =
+    clientIds === undefined ||
+    clientIds.length === 0 ||
+    clientIds.some((clientId) => clientId !== "claude_code");
+  return [
+    ...(includeShared
+      ? [
+          {
+            client: "shared" as const,
+            path: join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
+          },
+        ]
+      : []),
+    ...(includeClaude
+      ? [
+          {
+            client: "claude_code" as const,
+            path: join(claudeSkillsDirectory, PRODUCT_IDENTITY.skillName),
+          },
+        ]
+      : []),
+  ];
+};
 
 const readOptionalText = async (path: string): Promise => {
   try {
@@ -34,32 +83,39 @@ const readOptionalText = async (path: string): Promise => {
 
 const canonicalSkillFiles = async (
   home: string,
+  clientIds: readonly string[],
+  claudeSkillsDirectory?: string,
 ): Promise =>
   Promise.all(
-    SKILL_FILES.map(async (relativePath) => {
-      const destination = join(skillRoot(home), relativePath);
-      return {
-        destination,
-        content: await readFile(
-          new URL(
-            `../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
-            import.meta.url,
-          ),
-          "utf8",
-        ),
-        original: await readOptionalText(destination),
-      };
-    }),
+    skillDestinations(home, clientIds, claudeSkillsDirectory).flatMap(
+      ({ path: root }) =>
+        SKILL_FILES.map(async (relativePath) => {
+          const destination = join(root, relativePath);
+          return {
+            destination,
+            content: await readFile(
+              new URL(
+                `../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
+                import.meta.url,
+              ),
+              "utf8",
+            ),
+            original: await readOptionalText(destination),
+          };
+        }),
+    ),
   );
 
 /** Report whether setup would change any file in the managed REA skill bundle. */
 export const canonicalSkillNeedsInstall = async (
   home: string,
+  clientIds: readonly string[] = [],
+  claudeSkillsDirectory?: string,
 ): Promise => {
   try {
-    return (await canonicalSkillFiles(home)).some(
-      ({ content, original }) => original !== content,
-    );
+    return (
+      await canonicalSkillFiles(home, clientIds, claudeSkillsDirectory)
+    ).some(({ content, original }) => original !== content);
   } catch (cause: unknown) {
     // Unreadable skill state fails open to install so setup can repair it.
     void cause;
@@ -82,10 +138,16 @@ const restoreSkillFiles = async (
 /** Transactionally install or upgrade the canonical REA skill and references. */
 export const installCanonicalSkill = async (
   home: string,
+  clientIds: readonly string[] = [],
+  claudeSkillsDirectory?: string,
 ): Promise<"installed" | "unchanged" | "failed"> => {
   let changed: readonly CanonicalSkillFile[] = [];
   try {
-    const canonical = await canonicalSkillFiles(home);
+    const canonical = await canonicalSkillFiles(
+      home,
+      clientIds,
+      claudeSkillsDirectory,
+    );
     changed = canonical.filter(({ content, original }) => original !== content);
     if (changed.length === 0) return "unchanged";
 
@@ -112,3 +174,37 @@ export const installCanonicalSkill = async (
     return "failed";
   }
 };
+
+/** Read installed skill metadata and compare every managed location. */
+export const readInstalledSkillIdentity = async (
+  home: string,
+  clientIds: readonly string[],
+  claudeSkillsDirectory?: string,
+): Promise => {
+  const destinations = skillDestinations(
+    home,
+    clientIds,
+    claudeSkillsDirectory,
+  );
+  let content: string | undefined;
+  for (const destination of destinations) {
+    try {
+      content = await readFile(join(destination.path, "SKILL.md"), "utf8");
+      break;
+    } catch {
+      // Another selected copy may provide metadata; canonical validation below
+      // still marks missing or unreadable copies as stale.
+    }
+  }
+  if (content === undefined) return undefined;
+  const toolCount = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
+  return {
+    canonical: !(await canonicalSkillNeedsInstall(
+      home,
+      clientIds,
+      claudeSkillsDirectory,
+    )),
+    version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
+    toolCount: toolCount === undefined ? null : Number.parseInt(toolCount, 10),
+  };
+};
diff --git a/src/application/SetupTypes.ts b/src/application/SetupTypes.ts
index 75aed01bd..08eb0df99 100644
--- a/src/application/SetupTypes.ts
+++ b/src/application/SetupTypes.ts
@@ -42,6 +42,7 @@ export type ClientConfigurationInspection =
 export interface SetupHost {
   readonly platform: NodeJS.Platform;
   readonly homeDirectory: string;
+  readonly claudeCodeSkillsDirectory: string;
   readonly registrationCommand: readonly string[];
   readonly nodeVersion: string;
   macosVersion(): Promise;
@@ -65,8 +66,10 @@ export interface SetupHost {
     providerEnvironment: SetupProviderEnvironment,
     command: readonly string[],
   ): Promise;
-  skillNeedsInstall(): Promise;
-  installSkill(): Promise<"installed" | "unchanged" | "failed">;
+  skillNeedsInstall(clientIds: readonly string[]): Promise;
+  installSkill(
+    clientIds: readonly string[],
+  ): Promise<"installed" | "unchanged" | "failed">;
   doctor(scope?: DoctorScope): Promise>>;
 }
 /** Structured setup outcome carrying remediation instead of prompting. */
diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts
index f05224adb..9848e91da 100644
--- a/src/application/Uninstall.ts
+++ b/src/application/Uninstall.ts
@@ -15,6 +15,7 @@ import writeFileAtomic from "write-file-atomic";
 import { z } from "zod";
 
 import { PRODUCT_IDENTITY } from "../identity.js";
+import { claudeCodeSkillsDirectory, skillDestinations } from "./SetupSkill.js";
 import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
 import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
 import {
@@ -178,7 +179,7 @@ export const systemUninstallHost = (
         : undefined;
     },
     removeClient: (client) => removeClient(client, fileSystem),
-    removeSkill: () => removeManagedSkills(home, fileSystem),
+    removeSkill: () => removeManagedSkills(home, fileSystem, environment),
     purgeData: async () => [
       await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
       await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
@@ -402,12 +403,48 @@ const removeManagedPath = async (
 const removeManagedSkills = async (
   home: string,
   fileSystem: UninstallFileSystem,
-): Promise =>
-  removeManagedPath(
-    join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
-    "skill",
-    fileSystem,
+  environment: Readonly,
+): Promise => {
+  const results = await Promise.all(
+    skillDestinations(
+      home,
+      undefined,
+      claudeCodeSkillsDirectory(home, environment),
+    ).map(({ client, path }) =>
+      removeManagedPath(
+        path,
+        client === "claude_code" ? "Claude Code skill" : "skill",
+        fileSystem,
+      ),
+    ),
   );
+  const failed = results.find(({ status }) => status === "failed");
+  if (failed !== undefined)
+    return item(
+      "skill",
+      "failed",
+      results
+        .map(({ name, status, detail }) => `${name}: ${status} (${detail})`)
+        .join(" "),
+    );
+  const status = results.some(
+    ({ status: resultStatus }) => resultStatus === "removed",
+  )
+    ? "removed"
+    : results.some(({ status: resultStatus }) => resultStatus === "retained")
+      ? "retained"
+      : "skipped";
+  return item(
+    "skill",
+    status,
+    results
+      .map(
+        ({ name, status: resultStatus, detail }) =>
+          `${name}: ${resultStatus} (${detail})`,
+      )
+      .join(" "),
+  );
+};
 
 const item = (
   name: string,
diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts
index 0a649610b..88eab9953 100644
--- a/tests/boundary/filesystem/clientLifecycle.test.ts
+++ b/tests/boundary/filesystem/clientLifecycle.test.ts
@@ -1629,14 +1629,41 @@ describe("client configuration filesystem failure reporting", () => {
         remove: () => Promise.reject(new Error("SECRET removal failure")),
       }),
     );
-    expect(result.items).toContainEqual({
-      name: "skill",
-      status: "failed",
-      detail:
-        "This item could not be removed. Check file permissions, then rerun uninstall.",
-    });
+    expect(result.items).toContainEqual(
+      expect.objectContaining({
+        name: "skill",
+        status: "failed",
+        detail: expect.stringContaining(
+          "This item could not be removed. Check file permissions, then rerun uninstall.",
+        ),
+      }),
+    );
     expect(JSON.stringify(result)).not.toContain("SECRET");
   });
+
+  it("uninstalls all managed skill roots, including a custom Claude Code directory", async () => {
+    const home = await createTestTempDirectory("rea-uninstall-skills-");
+    roots.push(home);
+    const customClaudeDirectory = join(home, "claude-config");
+    const rootsToRemove = [
+      join(home, ".agents/skills/reverse-engineer-anything"),
+      join(customClaudeDirectory, "skills/reverse-engineer-anything"),
+    ];
+    await Promise.all(
+      rootsToRemove.map((path) => mkdir(path, { recursive: true })),
+    );
+
+    const result = await systemUninstallHost(home, testFileSystem, {
+      CLAUDE_CONFIG_DIR: customClaudeDirectory,
+    }).removeSkill();
+
+    expect(result).toMatchObject({ status: "removed" });
+    await Promise.all(
+      rootsToRemove.map(async (path) => {
+        await expect(lstat(path)).rejects.toMatchObject({ code: "ENOENT" });
+      }),
+    );
+  });
 });
 
 const testFileSystem: UninstallFileSystem = {
diff --git a/tests/boundary/filesystem/setupSkill.test.ts b/tests/boundary/filesystem/setupSkill.test.ts
index e90adeb1b..0d1caa93a 100644
--- a/tests/boundary/filesystem/setupSkill.test.ts
+++ b/tests/boundary/filesystem/setupSkill.test.ts
@@ -1,11 +1,19 @@
 import { createHash } from "node:crypto";
-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import {
+  access,
+  chmod,
+  mkdir,
+  readFile,
+  rm,
+  writeFile,
+} from "node:fs/promises";
 import { dirname, join } from "node:path";
 import { describe, expect, it } from "vitest";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
 
 import {
   canonicalSkillNeedsInstall,
+  claudeCodeSkillsDirectory,
   installCanonicalSkill,
 } from "../../../src/application/SetupSkill.js";
 import {
@@ -18,6 +26,127 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
 import { z } from "zod";
 import { skillReferenceIssues } from "../../../scripts/lib/docs-facts.mjs";
 
+describe("canonical skill transaction", () => {
+  it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+    "preserves an unreadable existing skill instead of treating it as absent",
+    async () => {
+      const home = await createTestTempDirectory("rea-skill-unreadable-");
+      const destination = join(
+        home,
+        ".agents/skills/reverse-engineer-anything/SKILL.md",
+      );
+      const original = "existing private skill bytes\n";
+      await mkdir(dirname(destination), { recursive: true });
+      await writeFile(destination, original, { mode: 0o200 });
+      try {
+        await chmod(destination, 0o200);
+        expect(await installCanonicalSkill(home)).toBe("failed");
+      } finally {
+        await chmod(destination, 0o600);
+      }
+      expect(await readFile(destination, "utf8")).toBe(original);
+      await expect(
+        readFile(`${destination}.rea.backup`, "utf8"),
+      ).rejects.toMatchObject({
+        code: "ENOENT",
+      });
+    },
+  );
+
+  it("installs only the selected Claude Code personal skill", async () => {
+    const home = await createTestTempDirectory("rea-claude-skill-");
+    const configDirectory = join(home, "claude-config");
+    const skillsDirectory = claudeCodeSkillsDirectory(home, {
+      CLAUDE_CONFIG_DIR: configDirectory,
+    });
+    const claudeSkill = join(
+      skillsDirectory,
+      "reverse-engineer-anything/SKILL.md",
+    );
+    await mkdir(configDirectory, { recursive: true });
+    await writeFile(
+      join(configDirectory, ".claude.json"),
+      JSON.stringify({
+        mcpServers: {
+          rea: {
+            command: "npx",
+            args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
+          },
+        },
+      }),
+    );
+    const host = systemDoctorHost({
+      environment: {
+        HOME: home,
+        USERPROFILE: home,
+        CLAUDE_CONFIG_DIR: configDirectory,
+      },
+    });
+
+    expect(
+      await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
+    ).toBe(true);
+    expect(
+      await installCanonicalSkill(home, ["claude_code"], skillsDirectory),
+    ).toBe("installed");
+    expect(
+      await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
+    ).toBe(false);
+    await expect(access(claudeSkill)).resolves.toBeUndefined();
+    await expect(
+      access(join(home, ".agents/skills/reverse-engineer-anything")),
+    ).rejects.toMatchObject({ code: "ENOENT" });
+    expect(
+      (
+        await runDoctor(undefined, host, {
+          clients: ["claude_code"],
+          skill: true,
+        })
+      ).identity?.skill.state,
+    ).toBe("aligned");
+  });
+
+  it("checks selected skill locations for independent drift", async () => {
+    const home = await createTestTempDirectory("rea-mixed-skill-");
+    const sharedSkill = join(
+      home,
+      ".agents/skills/reverse-engineer-anything/SKILL.md",
+    );
+    const claudeSkills = claudeCodeSkillsDirectory(home);
+    const claudeSkill = join(
+      claudeSkills,
+      "reverse-engineer-anything/SKILL.md",
+    );
+    const host = systemDoctorHost({
+      environment: { HOME: home, USERPROFILE: home },
+    });
+    const doctorScope = { clients: ["claude_code", "codex"], skill: true };
+
+    expect(await installCanonicalSkill(home, ["claude_code", "codex"])).toBe(
+      "installed",
+    );
+    await rm(sharedSkill);
+    expect(
+      (await runDoctor(undefined, host, doctorScope)).identity?.skill.state,
+    ).toBe("stale");
+    expect(await installCanonicalSkill(home, ["claude_code", "codex"])).toBe(
+      "installed",
+    );
+    for (const skill of [sharedSkill, claudeSkill]) {
+      await writeFile(skill, "selected copy changed\n");
+      expect(
+        (await runDoctor(undefined, host, doctorScope)).identity?.skill.state,
+      ).toBe("stale");
+      expect(await installCanonicalSkill(home, ["claude_code", "codex"])).toBe(
+        "installed",
+      );
+      expect(
+        (await runDoctor(undefined, host, doctorScope)).identity?.skill.state,
+      ).toBe("aligned");
+    }
+  });
+});
+
 describe("canonical skill transaction", () => {
   it("backs up and upgrades a stale managed skill without touching siblings", async () => {
     const home = await createTestTempDirectory("rea-skill-test-");
@@ -90,7 +219,6 @@ describe("canonical skill transaction", () => {
     expect(installedSkill).toContain(
       `tool_count: ${String(TOOL_CONTRACTS.length)}`,
     );
-    expect(installedSkill).not.toContain("catalog_digest:");
     expect(await readFile(sibling, "utf8")).toBe("unrelated skill\n");
     expect(
       await readFile(
@@ -160,8 +288,9 @@ it("doctor verifies installed instructions and references even when metadata is
     environment: { HOME: home, USERPROFILE: home },
   });
   const host = createDoctorHostFixture({
-    installedSkillIdentity: () =>
-      system.installedSkillIdentity?.() ?? Promise.resolve(undefined),
+    installedSkillIdentity: (registrations) =>
+      system.installedSkillIdentity?.(registrations) ??
+      Promise.resolve(undefined),
   });
   expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
     "missing",
@@ -169,24 +298,14 @@ it("doctor verifies installed instructions and references even when metadata is
   expect(await installCanonicalSkill(home)).toBe("installed");
   expect((await runDoctor(undefined, host)).identity?.skill).toMatchObject({
     state: "aligned",
-    installed_catalog_digest: null,
   });
-  const legacyDigest = "0".repeat(64);
-  await writeFile(
-    destination,
-    (await readFile(destination, "utf8")).replace(
-      `  tool_count: ${String(TOOL_CONTRACTS.length)}`,
-      `  tool_count: ${String(TOOL_CONTRACTS.length)}\n  catalog_digest: "${legacyDigest}"`,
-    ),
-  );
-  expect((await runDoctor(undefined, host)).identity?.skill).toMatchObject({
-    state: "stale",
-    installed_catalog_digest: legacyDigest,
-  });
-  expect(await installCanonicalSkill(home)).toBe("installed");
-  for (const path of [destination, reference]) {
-    const canonical = await readFile(path, "utf8");
-    await writeFile(path, `${canonical}\nLocally changed instructions.\n`);
+  for (const [path, remove] of [
+    [destination, false],
+    [reference, false],
+    [reference, true],
+  ] as const) {
+    if (remove) await rm(path);
+    else await writeFile(path, "Locally changed instructions.\n");
     expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
       "stale",
     );
@@ -195,12 +314,4 @@ it("doctor verifies installed instructions and references even when metadata is
       "aligned",
     );
   }
-  await rm(reference);
-  expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
-    "stale",
-  );
-  expect(await installCanonicalSkill(home)).toBe("installed");
-  expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
-    "aligned",
-  );
 });

From 449d57075eec71b2f064af8877c50cbbde30a283 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:15:51 +0800
Subject: [PATCH 062/189] refactor(javascript)!: remove obsolete scope
 truncation statistic

BREAKING CHANGE: remove the never-incremented truncated_scopes statistic from JavaScript application analysis results and schemas.
---
 .../javascript/JavaScriptArtifactAnalysis.ts        |  7 -------
 .../javascript/JavaScriptArtifactAnalysisTypes.ts   |  1 -
 .../javascript/JavaScriptArtifactGraphBuilder.ts    |  2 --
 .../javascript/JavaScriptArtifactReconstruction.ts  |  3 ---
 .../JavaScriptSemanticGraphBuilder.test.ts          |  1 -
 .../javascript/JavaScriptSemanticGraphBuilder.ts    | 13 ++++---------
 .../javascript/JavaScriptSemanticGraphProjection.ts |  6 ++----
 .../JavaScriptSemanticGraphResources.test.ts        |  2 --
 .../javascript/JavaScriptSemanticGraphScope.test.ts |  1 -
 .../javascriptExportShapeComparisonExample.ts       |  1 -
 .../javascriptRuntimeReconciliationExample.ts       |  1 -
 .../javascript/javascriptApplicationAnalysis.ts     |  1 -
 .../javascriptArtifactReconstruction.test.ts        |  6 +-----
 13 files changed, 7 insertions(+), 38 deletions(-)

diff --git a/src/application/javascript/JavaScriptArtifactAnalysis.ts b/src/application/javascript/JavaScriptArtifactAnalysis.ts
index 7433af4be..84390b873 100644
--- a/src/application/javascript/JavaScriptArtifactAnalysis.ts
+++ b/src/application/javascript/JavaScriptArtifactAnalysis.ts
@@ -47,7 +47,6 @@ interface MutableArtifactAnalysis<
   findings: number;
   modules: number;
   parseFailures: number;
-  truncatedScopes: number;
 }
 
 interface ArtifactAnalysisContext<
@@ -132,7 +131,6 @@ const finalizeArtifactAnalysis = <
 >(
   state: MutableArtifactAnalysis,
 ): JavaScriptArtifactAnalysis => {
-  const truncatedScopes = state.truncatedScopes;
   return {
     files: state.files,
     packages: state.packages,
@@ -143,13 +141,9 @@ const finalizeArtifactAnalysis = <
     findings: state.findings + state.htmlScripts.length,
     modules: state.modules,
     parse_failures: state.parseFailures,
-    truncated_scopes: truncatedScopes,
     limitations: [
       "JavaScript and HTML were parsed as inert text; bundle bootstrap code was never executed.",
       "Static paths and relationships may remain unresolved when expressions are dynamic or obfuscated.",
-      ...(truncatedScopes === 0
-        ? []
-        : ["Some static-analysis scopes were truncated."]),
     ],
   };
 };
@@ -222,7 +216,6 @@ const emptyArtifactAnalysis = <
   findings: 0,
   modules: 0,
   parseFailures: 0,
-  truncatedScopes: 0,
 });
 
 const addStructuredObservations = (
diff --git a/src/application/javascript/JavaScriptArtifactAnalysisTypes.ts b/src/application/javascript/JavaScriptArtifactAnalysisTypes.ts
index 7eb9268a6..261ac88ec 100644
--- a/src/application/javascript/JavaScriptArtifactAnalysisTypes.ts
+++ b/src/application/javascript/JavaScriptArtifactAnalysisTypes.ts
@@ -123,7 +123,6 @@ export interface JavaScriptArtifactAnalysis<
   readonly findings: number;
   readonly modules: number;
   readonly parse_failures: number;
-  readonly truncated_scopes: number;
   readonly limitations: readonly string[];
 }
 
diff --git a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
index 29648aa44..bf46a0557 100644
--- a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
@@ -132,8 +132,6 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
     sourceMapPolicyGap ||
     malformedStructuredData ||
     partialJavaScript;
-  if (context.analysis.truncated_scopes > 0)
-    return partialApplicationCoverage([], null);
   if (resourceLimits.length > 0)
     return partialApplicationCoverage(
       semanticResourceLimitCoverage(resourceLimits),
diff --git a/src/application/javascript/JavaScriptArtifactReconstruction.ts b/src/application/javascript/JavaScriptArtifactReconstruction.ts
index 39ff299f3..ab986608a 100644
--- a/src/application/javascript/JavaScriptArtifactReconstruction.ts
+++ b/src/application/javascript/JavaScriptArtifactReconstruction.ts
@@ -49,7 +49,6 @@ export interface JavaScriptArtifactReconstructionResult {
     readonly findings: number;
     readonly modules: number;
     readonly parse_failures: number;
-    readonly truncated_scopes: number;
   };
   readonly limitations: readonly string[];
 }
@@ -129,7 +128,6 @@ export const reconstructJavaScriptArtifact = async (
     const semanticGraphSteps = semanticProjection.finishImmutableSteps(
       snapshot.manifest.root_sha256,
       graph,
-      analysis,
     );
     await reportPhase(
       "seal_javascript_semantic_graph",
@@ -162,7 +160,6 @@ export const reconstructJavaScriptArtifact = async (
         findings: analysis.findings,
         modules: analysis.modules,
         parse_failures: analysis.parse_failures,
-        truncated_scopes: analysis.truncated_scopes,
       },
       limitations: analysis.limitations,
     };
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
index 6dd3f8576..54ecec21e 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
@@ -380,7 +380,6 @@ const graphFor = (source: string, ir = analyzeJavaScriptSemantics(source)) => {
     findings: 0,
     modules: 0,
     parse_failures: 0,
-    truncated_scopes: 0,
     limitations: [],
   };
   return buildJavaScriptSemanticGraph({
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
index e7190baec..7736c1010 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
@@ -118,7 +118,7 @@ export const buildJavaScriptSemanticGraph = ({
     if (analyzed.semantic !== null)
       projection.projectFile(analyzed.file, analyzed.semantic.ir);
   }
-  return projection.finish(rootArtifactSha256, applicationGraph, analysis);
+  return projection.finish(rootArtifactSha256, applicationGraph);
 };
 
 /** File-local semantic projection that does not retain consumed source IR. */
@@ -130,12 +130,10 @@ export interface JavaScriptSemanticGraphProjection {
   readonly finish: (
     rootArtifactSha256: string,
     applicationGraph: BuilderInput["applicationGraph"],
-    analysis: Pick,
   ) => JavaScriptSemanticGraph;
   readonly finishImmutableSteps: (
     rootArtifactSha256: string,
     applicationGraph: BuilderInput["applicationGraph"],
-    analysis: Pick,
   ) => Generator;
 }
 
@@ -171,7 +169,6 @@ export const createJavaScriptSemanticGraphProjection =
       factory: (input: unknown) => Value,
       rootArtifactSha256: string,
       applicationGraph: BuilderInput["applicationGraph"],
-      analysis: Pick,
     ): Value => {
       bindSemanticGraphApplicationNodes(state, applicationGraph);
       if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
@@ -202,7 +199,7 @@ export const createJavaScriptSemanticGraphProjection =
               : [],
           families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
             family,
-            status: semanticFamilyStatus(family, analysis),
+            status: semanticFamilyStatus(family),
             retained_relations: [...state.relations.values()].filter(
               (relation) =>
                 JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] ===
@@ -237,19 +234,17 @@ export const createJavaScriptSemanticGraphProjection =
     };
     return {
       projectFile: projectSource,
-      finish: (rootArtifactSha256, applicationGraph, analysis) =>
+      finish: (rootArtifactSha256, applicationGraph) =>
         finishWith(
           createJavaScriptSemanticGraph,
           rootArtifactSha256,
           applicationGraph,
-          analysis,
         ),
-      finishImmutableSteps: (rootArtifactSha256, applicationGraph, analysis) =>
+      finishImmutableSteps: (rootArtifactSha256, applicationGraph) =>
         finishWith(
           createImmutableJavaScriptSemanticGraphSteps,
           rootArtifactSha256,
           applicationGraph,
-          analysis,
         ),
     };
   };
diff --git a/src/application/javascript/JavaScriptSemanticGraphProjection.ts b/src/application/javascript/JavaScriptSemanticGraphProjection.ts
index 182a67612..bc1ade297 100644
--- a/src/application/javascript/JavaScriptSemanticGraphProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphProjection.ts
@@ -3,7 +3,6 @@ import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javasc
 import { JAVASCRIPT_SEMANTIC_RELATION_FAMILIES } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
 import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
-import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
 
 interface SourceInterval {
   readonly range: JavaScriptSourceRange;
@@ -171,8 +170,7 @@ const rangeKey = (range: JavaScriptSourceRange): string =>
 /** Report extractor support without treating missing families as absence. */
 export const semanticFamilyStatus = (
   family: (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number],
-  analysis: Pick,
-): "complete" | "partial" | "unknown" | "unsupported" => {
+): "partial" | "unsupported" => {
   if (
     ![
       "call-flow",
@@ -190,7 +188,7 @@ export const semanticFamilyStatus = (
     ].includes(family)
   )
     return "unsupported";
-  return analysis.truncated_scopes === 0 ? "partial" : "unknown";
+  return "partial";
 };
 
 const contains = (
diff --git a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
index 2f6efff32..6f7776011 100644
--- a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
@@ -352,7 +352,6 @@ const emptyAnalysis = (): JavaScriptArtifactAnalysis => ({
   findings: 0,
   modules: 0,
   parse_failures: 0,
-  truncated_scopes: 0,
   limitations: [],
 });
 
@@ -385,7 +384,6 @@ const graphFor = (source: string) => {
     findings: 0,
     modules: 0,
     parse_failures: 0,
-    truncated_scopes: 0,
     limitations: [],
   };
   return buildJavaScriptSemanticGraph({
diff --git a/src/application/javascript/JavaScriptSemanticGraphScope.test.ts b/src/application/javascript/JavaScriptSemanticGraphScope.test.ts
index cb4a3b7de..fca97b81a 100644
--- a/src/application/javascript/JavaScriptSemanticGraphScope.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphScope.test.ts
@@ -36,7 +36,6 @@ const graphFor = (source: string) => {
     findings: 0,
     modules: 0,
     parse_failures: 0,
-    truncated_scopes: 0,
     limitations: [],
   };
   return buildJavaScriptSemanticGraph({
diff --git a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
index 2fb7b96cc..221367859 100644
--- a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
+++ b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
@@ -74,7 +74,6 @@ const statistics = {
   findings: 1,
   modules: 0,
   parse_failures: 0,
-  truncated_scopes: 0,
 };
 const modulePath = "parser.mjs";
 const limitations = [
diff --git a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
index bd3991dd6..c6eacc8a9 100644
--- a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
+++ b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
@@ -164,7 +164,6 @@ export const JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE = createEvidence(
         findings: 0,
         modules: 0,
         parse_failures: 0,
-        truncated_scopes: 0,
       },
       limitations: [],
     },
diff --git a/src/domain/javascript/javascriptApplicationAnalysis.ts b/src/domain/javascript/javascriptApplicationAnalysis.ts
index 8d976d7fb..4360f4190 100644
--- a/src/domain/javascript/javascriptApplicationAnalysis.ts
+++ b/src/domain/javascript/javascriptApplicationAnalysis.ts
@@ -59,7 +59,6 @@ const reconstructionStatisticsSchema = z.strictObject({
   findings: countSchema,
   modules: countSchema,
   parse_failures: countSchema,
-  truncated_scopes: countSchema,
 });
 
 const applicationAnalysisResultShape = z.strictObject({
diff --git a/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts b/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
index a75db7b0a..2775b0cb8 100644
--- a/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
+++ b/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
@@ -70,11 +70,7 @@ it("preserves graph commitments and export shapes when consuming file-local IR",
     expect(buildJavaScriptArtifactGraph(snapshot, files, compact)).toEqual(
       graph,
     );
-    const semantic = projection.finish(
-      snapshot.manifest.root_sha256,
-      graph,
-      compact,
-    );
+    const semantic = projection.finish(snapshot.manifest.root_sha256, graph);
     expect(semantic).toEqual(
       buildJavaScriptSemanticGraph({
         rootArtifactSha256: snapshot.manifest.root_sha256,

From c867bcd0aadd63473865f9a328459e0db3c89565 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:21:54 +0800
Subject: [PATCH 063/189] test(javascript): share primitive expansion producer
 fixtures

---
 .../JavaScriptSemanticGraphBuilder.test.ts    | 11 ++-------
 .../javascriptIntegrityPolicy.test.ts         | 20 +++++-----------
 .../javascriptArtifactReconstruction.test.ts  | 23 +++++--------------
 .../fixtures/javascriptPrimitiveExpansion.ts  | 21 +++++++++++++++++
 4 files changed, 35 insertions(+), 40 deletions(-)
 create mode 100644 tests/fixtures/javascriptPrimitiveExpansion.ts

diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
index 54ecec21e..43d63a7d0 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts
@@ -1,3 +1,4 @@
+import { primitiveByteExpansionSource } from "../../../tests/fixtures/javascriptPrimitiveExpansion.js";
 import * as t from "@babel/types";
 import { expect, it } from "vitest";
 
@@ -111,15 +112,7 @@ it("preserves primitive candidate budget unknowns in semantic graph coverage", (
 });
 
 it("preserves derived string-byte limit reasons in semantic graph unknowns", () => {
-  const declarations = ['const value0 = "x";'];
-  for (let index = 1; index <= 30; index += 1) {
-    const previous = `value${String(index - 1)}`;
-    declarations.push(
-      `const value${String(index)} = ${previous} + ${previous};`,
-    );
-  }
-  declarations.push("const answer = value30;");
-  const source = declarations.join("\n");
+  const source = primitiveByteExpansionSource();
   const ir = analyzeJavaScriptSemantics(source);
   const graph = graphFor(source, ir);
 
diff --git a/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
index 7291d888e..9fd482ec2 100644
--- a/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
+++ b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
@@ -1,3 +1,7 @@
+import {
+  primitiveCandidateExpansionSource,
+  primitiveByteExpansionSource,
+} from "../../fixtures/javascriptPrimitiveExpansion.js";
 import { createHash } from "node:crypto";
 import { mkdir, readFile, writeFile } from "node:fs/promises";
 import { join } from "node:path";
@@ -102,21 +106,9 @@ it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", a
 });
 
 it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
-  const expression = Array.from(
-    { length: 20 },
-    () => '(true ? "a" : "b")',
-  ).join(" + ");
-  const declarations = ['const value0 = "x";'];
-  for (let index = 1; index <= 30; index += 1) {
-    const previous = `value${String(index - 1)}`;
-    declarations.push(
-      `const value${String(index)} = ${previous} + ${previous};`,
-    );
-  }
-  declarations.push("const answer = value30;");
   const { archive } = await createStrippedAsarAddon([
-    { path: "app.js", contents: `const answer = { nested: ${expression} };` },
-    { path: "growth.js", contents: declarations.join("\n") },
+    { path: "app.js", contents: primitiveCandidateExpansionSource() },
+    { path: "growth.js", contents: primitiveByteExpansionSource() },
   ]);
   const analyzed = await analyzeJavaScriptApplication({
     input_path: archive,
diff --git a/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts b/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
index 2775b0cb8..4bbc2eb36 100644
--- a/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
+++ b/tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts
@@ -1,3 +1,7 @@
+import {
+  primitiveCandidateExpansionSource,
+  primitiveByteExpansionSource,
+} from "../../fixtures/javascriptPrimitiveExpansion.js";
 import { createHash } from "node:crypto";
 import { mkdir, rm, writeFile } from "node:fs/promises";
 import { join } from "node:path";
@@ -102,23 +106,8 @@ it("preserves graph commitments and export shapes when consuming file-local IR",
 
 it("reports semantic value resource limits in application graph coverage", async () => {
   const root = await createTestTempDirectory("rea-javascript-semantic-limit-");
-  const expression = Array.from(
-    { length: 20 },
-    () => '(true ? "a" : "b")',
-  ).join(" + ");
-  await writeFile(
-    join(root, "app.js"),
-    `const answer = { nested: ${expression} };`,
-  );
-  const declarations = ['const value0 = "x";'];
-  for (let index = 1; index <= 30; index += 1) {
-    const previous = `value${String(index - 1)}`;
-    declarations.push(
-      `const value${String(index)} = ${previous} + ${previous};`,
-    );
-  }
-  declarations.push("const answer = value30;");
-  await writeFile(join(root, "growth.js"), declarations.join("\n"));
+  await writeFile(join(root, "app.js"), primitiveCandidateExpansionSource());
+  await writeFile(join(root, "growth.js"), primitiveByteExpansionSource());
   const snapshot = await scanCanonicalArtifactInventory(root, {});
   const reader = createJavaScriptArtifactReader(root, "directory");
   try {
diff --git a/tests/fixtures/javascriptPrimitiveExpansion.ts b/tests/fixtures/javascriptPrimitiveExpansion.ts
new file mode 100644
index 000000000..1189dc902
--- /dev/null
+++ b/tests/fixtures/javascriptPrimitiveExpansion.ts
@@ -0,0 +1,21 @@
+/** Source whose concatenated alternatives exceed primitive candidate storage. */
+export const primitiveCandidateExpansionSource = (): string => {
+  const expression = Array.from(
+    { length: 20 },
+    () => '(true ? "a" : "b")',
+  ).join(" + ");
+  return `const answer = { nested: ${expression} };`;
+};
+
+/** Source whose repeated doubling exceeds derived primitive string storage. */
+export const primitiveByteExpansionSource = (): string => {
+  const declarations = ['const value0 = "x";'];
+  for (let index = 1; index <= 30; index += 1) {
+    const previous = `value${String(index - 1)}`;
+    declarations.push(
+      `const value${String(index)} = ${previous} + ${previous};`,
+    );
+  }
+  declarations.push("const answer = value30;");
+  return declarations.join("\n");
+};

From a959a8309db79fbee6477efd7ee541615e625627 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:37:03 +0800
Subject: [PATCH 064/189] test(json): remove assertions covered by CLI output
 consumers

---
 src/domain/jsonSerialization.test.ts | 10 ----------
 1 file changed, 10 deletions(-)

diff --git a/src/domain/jsonSerialization.test.ts b/src/domain/jsonSerialization.test.ts
index 45caf7898..560b89d29 100644
--- a/src/domain/jsonSerialization.test.ts
+++ b/src/domain/jsonSerialization.test.ts
@@ -36,16 +36,6 @@ describe("streamed JSON representation", () => {
     expect(JSON.parse(parts.join(""))).toEqual(value);
   });
 
-  it("rejects a cycle while allowing repeated references", () => {
-    const shared = { value: 1 };
-    expect([...jsonParts({ left: shared, right: shared })].join("")).toBe(
-      JSON.stringify({ left: shared, right: shared }),
-    );
-    const cycle: { self?: unknown } = {};
-    cycle.self = cycle;
-    expect(() => [...jsonParts(cycle)]).toThrow("circular reference");
-  });
-
   it("matches existing canonical bytes for numeric keys, Unicode, and shared values", () => {
     const shared = { z: -0, a: [1e-7, 1e30, "雪😀\ud800"] };
     const ownKeys: unknown = JSON.parse(

From e36afa112fd7b7ab5a925ca452de93b68f12a6ab Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:45:03 +0800
Subject: [PATCH 065/189] docs(contracts)!: explain canonical URL and skill
 metadata ownership

BREAKING CHANGE: source-map URLs now live in target observations selected by declared_url_sha256, and doctor skill identity no longer emits installed_catalog_digest. Use the documented observation join and identity.skill.state instead.
---
 docs/installation.md                       | 6 ++++++
 docs/javascript-application-graph.md       | 4 ++++
 docs/javascript-artifact-reconstruction.md | 7 +++++++
 3 files changed, 17 insertions(+)

diff --git a/docs/installation.md b/docs/installation.md
index fecbe4aa0..1152dd848 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -199,6 +199,12 @@ use the shared `~/.agents/skills` directory. A mixed selection plans both
 paths. Selecting the skill without a client uses the shared directory. Setup
 leaves existing skill copies in other locations untouched.
 
+`doctor --skill --json` verifies the selected copies against the bundled
+instructions and references. Consumers should use `identity.skill.state`,
+`installed_version`, and `installed_tool_count` for skill readiness. The
+obsolete `installed_catalog_digest` field has been removed; current catalog
+identity remains available at `identity.catalog`.
+
 After selection, review the plan's exact paths and changes and approve before
 REA writes files or installs Hopper. You can cancel at any prompt.
 
diff --git a/docs/javascript-application-graph.md b/docs/javascript-application-graph.md
index fd87b00ee..2290491a5 100644
--- a/docs/javascript-application-graph.md
+++ b/docs/javascript-application-graph.md
@@ -81,6 +81,10 @@ one physical source map. The full URL is kept out of node identity, display
 label, and edge properties, so large inline data URLs are stored once per
 source-map reference.
 
+Consumers previously reading `edge.properties.declared_url` should follow
+`target_node_id` and select the observation by `declared_url_sha256` instead.
+Node labels serve display; the observation preserves the original URL.
+
 For example, a source-owned synthetic fixture proves this path without using a
 third-party application:
 
diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md
index 372934b7a..881b244d6 100644
--- a/docs/javascript-artifact-reconstruction.md
+++ b/docs/javascript-artifact-reconstruction.md
@@ -112,6 +112,13 @@ Field selection remains useful when the caller needs a
 smaller view, for example `--format json --filter-output
 evidence_id,normalized_result.statistics`. Streaming output does not bound the
 memory needed to construct the analysis graph itself.
+
+CLI workflows still parse each JSON input as one value. A valid input exceeding
+the Node runtime's maximum string length returns `resource_constraint` with
+`input_reason: "too-large"` and the runtime limit. Produce smaller independent
+analysis inputs before retrying; streaming output does not imply streaming
+input parsing.
+
 MCP prepares the complete repeated response incrementally against the pinned
 SDK's 10 MiB stdio receive-buffer budget. Oversized results return an actionable
 transport constraint and the exact same-session Evidence reference. Use

From 750fb6565052e9eaad40b946b6a284d0730d14f8 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 02:48:10 +0800
Subject: [PATCH 066/189] refactor(artifacts): test inventory changes at
 materialization boundary

---
 .../extraction/ArtifactExtraction.ts          |  12 ++
 ...actProvider.extractionCompleteness.test.ts | 106 ++++++------------
 2 files changed, 46 insertions(+), 72 deletions(-)

diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts
index 8e40d6cc5..89c6291a7 100644
--- a/src/artifacts/extraction/ArtifactExtraction.ts
+++ b/src/artifacts/extraction/ArtifactExtraction.ts
@@ -26,6 +26,7 @@ import {
 } from "../../domain/artifactGraph.js";
 import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js";
 import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
+import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
 import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
 
 /** Local extraction input with the output root chosen by the adapter. */
@@ -49,6 +50,17 @@ export const extractArtifact = async (
     signal,
     environment: input.environment,
   });
+  return materializeArtifactInventory(input, sourcePath, snapshot, signal);
+};
+
+/** Materialize a scanned inventory, verifying every current occurrence against it. */
+export const materializeArtifactInventory = async (
+  input: ArtifactExtractionInput,
+  sourcePath: string,
+  snapshot: ArtifactInventorySnapshot,
+  signal?: AbortSignal,
+): Promise => {
+  abortIfNeeded(signal);
   const selectedOccurrences = snapshot.occurrences.filter(
     (occurrence) =>
       (occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
diff --git a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
index 778a80f33..e7d593d61 100644
--- a/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
+++ b/tests/boundary/providers/native/artifactProvider.extractionCompleteness.test.ts
@@ -1,12 +1,13 @@
 import { createHash } from "node:crypto";
-import { watch } from "node:fs";
 import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
-import { basename, dirname, join } from "node:path";
+import { join } from "node:path";
 
 import { createPackage, createPackageWithOptions } from "@electron/asar";
-import { expect, it, onTestFinished } from "vitest";
+import { expect, it } from "vitest";
 
 import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
+import { materializeArtifactInventory } from "../../../../src/artifacts/extraction/ArtifactExtraction.js";
+import { scanArtifactInventory } from "../../../../src/artifacts/inventory/ArtifactInventory.js";
 import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
 import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
 import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -18,44 +19,22 @@ it.each(["file", "directory"] as const)(
     const source = join(root, "source");
     await mkdir(join(source, "z"), { recursive: true });
     // Equal bytes share an artifact node, but both occurrences must be copied.
-    const bytes = Buffer.alloc(8 * 1024 * 1024, "same bytes\n");
+    const bytes = Buffer.from("same bytes\n");
     await writeFile(join(source, "a.txt"), bytes);
     await writeFile(join(source, "z", "missing.txt"), bytes);
     const output = join(root, "output");
-    const changed = afterInventory(output, async () => {
-      await rm(
-        removedKind === "file"
-          ? join(source, "z", "missing.txt")
-          : join(source, "z"),
-        { recursive: removedKind === "directory" },
-      );
+    const materialize = await inventoriedExtraction(source, output);
+    await rm(
+      removedKind === "file"
+        ? join(source, "z", "missing.txt")
+        : join(source, "z"),
+      { recursive: removedKind === "directory" },
+    );
+    await expect(materialize()).rejects.toMatchObject({
+      reason: "integrity",
+      message:
+        "Inventoried regular artifact entries were not materialized: z/missing.txt",
     });
-
-    const result = await extract(source, output);
-    await changed();
-    if (result.ok) throw new Error("Incomplete extraction must fail");
-    const projected = projectAnalysisError(result.error);
-    expect(projected).toMatchObject({
-      code: "artifact_operation_failed",
-      details: {
-        operation: "extract_artifact",
-      },
-    });
-    // A directory already returned by readdir can disappear before its stat.
-    // That earlier reader failure retains ENOENT instead of reaching the final
-    // completeness check. Both paths must reject publication and roll back.
-    if (removedKind === "directory" && projected.details?.reason === "io") {
-      expect(projected.details).toMatchObject({
-        reason: "io",
-        detail: `Could not inspect entry at ${join(source, "z")} (ENOENT)`,
-      });
-    } else {
-      expect(projected.details).toMatchObject({
-        reason: "integrity",
-        detail:
-          "Inventoried regular artifact entries were not materialized: z/missing.txt",
-      });
-    }
     await expect(access(output)).rejects.toThrow();
     expect(
       createHash("sha256")
@@ -69,22 +48,13 @@ it("still refuses a regular file added after inventory and rolls back", async ()
   const root = await createTestTempDirectory("rea-extract-added-");
   const source = join(root, "source");
   await mkdir(source);
-  await writeFile(
-    join(source, "a.txt"),
-    Buffer.alloc(8 * 1024 * 1024, "original\n"),
-  );
+  await writeFile(join(source, "a.txt"), "original\n");
   const output = join(root, "output");
-  const changed = afterInventory(output, async () => {
-    await writeFile(join(source, "z.txt"), "new\n");
-  });
-  const result = await extract(source, output);
-  await changed();
-  if (result.ok) throw new Error("Changed inventory must fail");
-  expect(projectAnalysisError(result.error)).toMatchObject({
-    details: {
-      reason: "integrity",
-      detail: "Regular artifact entry is missing from inventory: z.txt",
-    },
+  const materialize = await inventoriedExtraction(source, output);
+  await writeFile(join(source, "z.txt"), "new\n");
+  await expect(materialize()).rejects.toMatchObject({
+    reason: "integrity",
+    message: "Regular artifact entry is missing from inventory: z.txt",
   });
   await expect(access(output)).rejects.toThrow();
 });
@@ -160,27 +130,19 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
   await expect(access(activeOutput)).rejects.toThrow();
 });
 
-// The real destination is created only after inventory. A streamed first file
-// leaves time to mutate a later entry without replacing any production method.
-const afterInventory = (output: string, change: () => Promise) => {
-  let mutation:
-    | Promise<{ ok: true } | { ok: false; cause: unknown }>
-    | undefined;
-  const watcher = watch(dirname(output), (_event, filename) => {
-    if (filename !== basename(output) || mutation !== undefined) return;
-    watcher.close();
-    mutation = change().then(
-      () => ({ ok: true as const }),
-      (cause: unknown) => ({ ok: false as const, cause }),
+const inventoriedExtraction = async (source: string, output: string) => {
+  const snapshot = await scanArtifactInventory(source);
+  return () =>
+    materializeArtifactInventory(
+      {
+        inputPath: source,
+        inputFormat: "asar",
+        outputRoot: output,
+        environment: process.env,
+      },
+      source,
+      snapshot,
     );
-  });
-  onTestFinished(() => watcher.close());
-  return async () => {
-    if (mutation === undefined)
-      throw new Error("Extraction destination was not observed");
-    const result = await mutation;
-    if (!result.ok) throw result.cause;
-  };
 };
 
 const extract = (source: string, output: string) =>

From 9c4a68bc19a0f7d39557e3cc039f5877f6550f63 Mon Sep 17 00:00:00 2001
From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
Date: Sat, 10 Oct 2026 03:39:35 +0800
Subject: [PATCH 067/189] fix(json): preserve runtime limits across JSON file
 readers (#1350)

* fix(cli): preserve runtime JSON string-limit diagnostics

* test(json): check actionable oversized Evidence recovery

* fix(json): decode large UTF-8 inputs by character length

* test(json): reject truncated UTF-8 after large input decode
---
 src/application/EvidenceBundleFiles.ts        |  10 +-
 src/application/JsonFiles.ts                  |  25 ++--
 src/application/Utf8JsonInput.ts              |  78 ++++++++++++
 .../binary/AnalysisSnapshotFiles.ts           |   5 +-
 src/cliJsonInput.ts                           | 114 ++++++++----------
 src/cliJsonInputStatus.test.ts                |   1 +
 tests/boundary/cli/jsonInputSize.test.ts      |  69 +++++++++++
 .../boundary/filesystem/cliJsonInput.test.ts  |  11 +-
 8 files changed, 232 insertions(+), 81 deletions(-)
 create mode 100644 src/application/Utf8JsonInput.ts
 create mode 100644 tests/boundary/cli/jsonInputSize.test.ts

diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts
index 487679070..4c7e310c7 100644
--- a/src/application/EvidenceBundleFiles.ts
+++ b/src/application/EvidenceBundleFiles.ts
@@ -9,7 +9,10 @@ import {
   EvidenceIntegrityError,
 } from "../domain/evidenceErrors.js";
 import { err, ok, type Result } from "../domain/result.js";
-import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
+import {
+  AnalysisCancelledError,
+  type AnalysisResourceConstraintError,
+} from "../domain/analysisErrorCore.js";
 import { parseProcessCapture } from "../domain/process/processCaptureParsing.js";
 import {
   bufferedJsonParts,
@@ -17,7 +20,10 @@ import {
 } from "../domain/jsonSerialization.js";
 import { readJsonFile, writeTextParts } from "./JsonFiles.js";
 
-type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
+type EvidenceReadFailure =
+  | EvidenceFileError
+  | EvidenceIntegrityError
+  | AnalysisResourceConstraintError;
 type EvidenceWriteFailure =
   | EvidenceFileError
   | EvidenceIntegrityError
diff --git a/src/application/JsonFiles.ts b/src/application/JsonFiles.ts
index cdf80d7e8..8132255da 100644
--- a/src/application/JsonFiles.ts
+++ b/src/application/JsonFiles.ts
@@ -12,8 +12,12 @@ import {
 import { basename, dirname, resolve } from "node:path";
 
 import { EvidenceFileError } from "../domain/evidenceErrors.js";
-import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
+import {
+  AnalysisCancelledError,
+  AnalysisResourceConstraintError,
+} from "../domain/analysisErrorCore.js";
 import { err, ok, type Result } from "../domain/result.js";
+import { parseUtf8Json } from "./Utf8JsonInput.js";
 
 /** Request control and its owning operation for an interruptible atomic write. */
 export interface TextWriteCancellation {
@@ -27,7 +31,9 @@ type TextWriteResult =
 /** Read JSON data from a regular file at the caller-supplied path. */
 export const readJsonFile = async (
   path: string,
-): Promise> => {
+): Promise<
+  Result
+> => {
   const requestedPath = resolve(path);
   try {
     const canonicalPath = await realpath(requestedPath);
@@ -37,23 +43,18 @@ export const readJsonFile = async (
         new EvidenceFileError("read", "not-file", { path: requestedPath }),
       );
     const encoded = await readFile(canonicalPath);
-    let decoded: unknown;
-    try {
-      decoded = JSON.parse(
-        new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
-          encoded,
-        ),
-      );
-    } catch (cause: unknown) {
+    const decoded = parseUtf8Json(encoded, "read_evidence_file", requestedPath);
+    if (!decoded.ok) {
       return err(
         new EvidenceFileError("read", "invalid-json", {
-          cause,
+          cause: decoded.cause,
           path: requestedPath,
         }),
       );
     }
-    return ok(decoded);
+    return ok(decoded.value);
   } catch (cause: unknown) {
+    if (cause instanceof AnalysisResourceConstraintError) return err(cause);
     return err(
       new EvidenceFileError("read", missingOrIo(cause), {
         cause,
diff --git a/src/application/Utf8JsonInput.ts b/src/application/Utf8JsonInput.ts
new file mode 100644
index 000000000..4b9ecf10b
--- /dev/null
+++ b/src/application/Utf8JsonInput.ts
@@ -0,0 +1,78 @@
+import { constants } from "node:buffer";
+
+import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
+import { safeParseJson, type SafeJsonParseResult } from "../domain/safeJson.js";
+
+/** Decode JSON bytes without confusing a runtime string limit with malformed input. */
+export const parseUtf8Json = (
+  bytes: Uint8Array,
+  operation: string,
+  path: string,
+  boundary = "json-input",
+): SafeJsonParseResult => {
+  const stringLimitFailure = (
+    cause?: unknown,
+    decodedUnits?: number,
+  ): AnalysisResourceConstraintError =>
+    new AnalysisResourceConstraintError(
+      operation,
+      "memory",
+      "JSON input exceeds the runtime's maximum decoded string length",
+      {
+        boundary,
+        input_path: path,
+        input_bytes: bytes.byteLength,
+        max_string_code_units: constants.MAX_STRING_LENGTH,
+        ...(decodedUnits === undefined
+          ? {}
+          : { decoded_string_code_units_at_least: decodedUnits }),
+      },
+      {
+        ...(cause === undefined ? {} : { cause }),
+        remediationAction:
+          "Provide a smaller JSON document. For Evidence-based workflows, re-analyze a smaller selection of the original target and use its Evidence; splitting JSON text alone does not produce a valid workflow input.",
+      },
+    );
+  let text: string;
+  try {
+    const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
+    if (bytes.byteLength <= constants.MAX_STRING_LENGTH) {
+      text = decoder.decode(bytes);
+    } else {
+      // Node 22's UTF-8 fast path bounds encoded bytes before decoding. Decode
+      // large inputs in chunks so valid multibyte text is bounded by its actual
+      // UTF-16 length. Streaming also preserves characters spanning chunks.
+      const parts: string[] = [];
+      let decodedUnits = 0;
+      const append = (part: string): void => {
+        decodedUnits += part.length;
+        if (decodedUnits > constants.MAX_STRING_LENGTH)
+          throw stringLimitFailure(undefined, decodedUnits);
+        parts.push(part);
+      };
+      const chunkBytes = 1024 * 1024;
+      for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes)
+        append(
+          decoder.decode(bytes.subarray(offset, offset + chunkBytes), {
+            stream: true,
+          }),
+        );
+      append(decoder.decode());
+      text = parts.join("");
+    }
+  } catch (cause: unknown) {
+    if (cause instanceof AnalysisResourceConstraintError) throw cause;
+    const code =
+      typeof cause === "object" && cause !== null && "code" in cause
+        ? cause.code
+        : undefined;
+    if (code === "ERR_STRING_TOO_LONG") throw stringLimitFailure(cause);
+    if (code !== "ERR_ENCODING_INVALID_ENCODED_DATA") throw cause;
+    return {
+      ok: false,
+      error: "JSON input is not valid UTF-8",
+      cause,
+    };
+  }
+  return safeParseJson(text);
+};
diff --git a/src/application/binary/AnalysisSnapshotFiles.ts b/src/application/binary/AnalysisSnapshotFiles.ts
index 2841e1dbf..87d910b5d 100644
--- a/src/application/binary/AnalysisSnapshotFiles.ts
+++ b/src/application/binary/AnalysisSnapshotFiles.ts
@@ -8,6 +8,7 @@ import {
   EvidenceIntegrityError,
 } from "../../domain/evidenceErrors.js";
 import { err, ok, type Result } from "../../domain/result.js";
+import type { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
 import { readJsonFile, writeTextFile } from "../JsonFiles.js";
 
 type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
@@ -15,7 +16,9 @@ type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
 /** Read and validate an analysis snapshot from the caller's path. */
 export const readAnalysisSnapshot = async (
   path: string,
-): Promise> => {
+): Promise<
+  Result
+> => {
   const loaded = await readJsonFile(path);
   if (!loaded.ok) return loaded;
   try {
diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts
index 74dd30bc9..a47d1e5f5 100644
--- a/src/cliJsonInput.ts
+++ b/src/cliJsonInput.ts
@@ -5,6 +5,7 @@ import {
   NonRegularFileReadError,
   readRegularFile,
 } from "./application/RegularFileRead.js";
+import { parseUtf8Json } from "./application/Utf8JsonInput.js";
 import {
   AnalysisInputError,
   AnalysisResourceConstraintError,
@@ -21,18 +22,33 @@ export const parseCliJsonInput = async (
   | { readonly ok: true; readonly value: unknown }
   | { readonly ok: false; readonly error: JsonValue }
 > => {
-  const inline = parseJson(value);
-  if (inline.kind === "valid") return { ok: true, value: inline.value };
-  if (inline.kind === "too-large")
+  const inline = safeParseJson(value);
+  if (inline.ok) return { ok: true, value: inline.value };
+  if (isStringLengthLimit(inline.cause))
     return jsonTooLargeError(undefined, operation);
   try {
-    // Read raw bytes so invalid UTF-8 is rejected by parseJson instead of
+    // Read raw bytes so invalid UTF-8 is rejected instead of
     // being silently replaced by lossy "utf8" decoding.
-    const parsed = parseJson(await readRegularFile(value));
-    if (parsed.kind === "valid") return { ok: true, value: parsed.value };
-    if (parsed.kind === "too-large") return jsonTooLargeError(value, operation);
-    return jsonFileError(value, operation, "invalid-json");
+    const parsed = parseUtf8Json(
+      await readRegularFile(value),
+      operation,
+      value,
+      "cli-json-input",
+    );
+    return parsed.ok
+      ? { ok: true, value: parsed.value }
+      : jsonFileError(value, operation, "invalid-json");
   } catch (cause: unknown) {
+    if (cause instanceof AnalysisResourceConstraintError)
+      return {
+        ok: false,
+        error: {
+          error: "Application workflow failed",
+          ...projectAnalysisError(cause),
+          input_path: value,
+          input_reason: "too-large",
+        },
+      };
     if (
       ["{", "["].includes(value.trimStart()[0] ?? "") &&
       cannotBeAnExistingFile(cause) &&
@@ -93,39 +109,12 @@ const cannotBeAnExistingFile = (cause: unknown): boolean =>
 const hasExplicitJsonFileExtension = (value: string): boolean =>
   value.toLowerCase().endsWith(".json");
 
-type JsonParseResult =
-  | { readonly kind: "valid"; readonly value: unknown }
-  | { readonly kind: "invalid" }
-  | { readonly kind: "too-large" };
-
-const parseJson = (value: string | Uint8Array): JsonParseResult => {
-  let text: string;
-  if (typeof value === "string") {
-    text = value;
-  } else {
-    try {
-      text = new TextDecoder("utf-8", {
-        fatal: true,
-        ignoreBOM: true,
-      }).decode(value);
-    } catch (cause: unknown) {
-      return isStringLengthLimit(cause)
-        ? { kind: "too-large" }
-        : { kind: "invalid" };
-    }
-  }
-  const parsed = safeParseJson(text);
-  if (parsed.ok) return { kind: "valid", value: parsed.value };
-  return isStringLengthLimit(parsed.cause)
-    ? { kind: "too-large" }
-    : { kind: "invalid" };
-};
-
 const isStringLengthLimit = (cause: unknown): boolean =>
   cause instanceof Error &&
-  /cannot create a string longer than|invalid string length/i.test(
-    cause.message,
-  );
+  (("code" in cause && cause.code === "ERR_STRING_TOO_LONG") ||
+    /cannot create a string longer than|invalid string length/i.test(
+      cause.message,
+    ));
 
 const inputError = (operation: string): JsonValue => ({
   error: "Application workflow failed",
@@ -181,29 +170,26 @@ const readFailureIssue = (path: string | undefined, cause: unknown) => {
 const jsonTooLargeError = (
   path: string | undefined,
   operation: string,
-): { readonly ok: false; readonly error: JsonValue } => {
-  const projection = projectAnalysisError(
-    new AnalysisResourceConstraintError(
-      operation,
-      "memory",
-      `The JSON input exceeds this Node.js runtime's maximum string length (${bufferConstants.MAX_STRING_LENGTH} UTF-16 code units) and cannot be parsed as one value.`,
-      {
-        boundary: "cli-json-input",
-        max_string_code_units: bufferConstants.MAX_STRING_LENGTH,
-      },
-      {
-        remediationAction:
-          "Split the JSON into smaller inputs or rerun its producer on a smaller subset, then retry.",
-      },
+): { readonly ok: false; readonly error: JsonValue } => ({
+  ok: false,
+  error: {
+    error: "Application workflow failed",
+    ...projectAnalysisError(
+      new AnalysisResourceConstraintError(
+        operation,
+        "memory",
+        `The JSON input exceeds this Node.js runtime's maximum string length (${bufferConstants.MAX_STRING_LENGTH} UTF-16 code units) and cannot be parsed as one value.`,
+        {
+          boundary: "cli-json-input",
+          max_string_code_units: bufferConstants.MAX_STRING_LENGTH,
+        },
+        {
+          remediationAction:
+            "Provide a smaller JSON document or rerun its producer on a smaller selection. Splitting JSON text alone does not produce a valid workflow input.",
+        },
+      ),
     ),
-  );
-  return {
-    ok: false,
-    error: {
-      error: "Application workflow failed",
-      ...projection,
-      ...(path === undefined ? {} : { input_path: path }),
-      input_reason: "too-large",
-    },
-  };
-};
+    ...(path === undefined ? {} : { input_path: path }),
+    input_reason: "too-large",
+  },
+});
diff --git a/src/cliJsonInputStatus.test.ts b/src/cliJsonInputStatus.test.ts
index 8f9238e00..f4bf8854d 100644
--- a/src/cliJsonInputStatus.test.ts
+++ b/src/cliJsonInputStatus.test.ts
@@ -18,6 +18,7 @@ describe("CLI JSON input failure recognition", () => {
     { input_reason: "invalid-json" },
     { input_path: "input.json", input_reason: "invalid-json" },
     { input_path: "missing.json", input_reason: "read-failed" },
+    { input_path: "large.json", input_reason: "too-large" },
     { input_path: "", input_reason: "read-failed" },
   ])("recognizes a complete envelope with metadata %j", (metadata) => {
     const value = { ...envelope, ...metadata };
diff --git a/tests/boundary/cli/jsonInputSize.test.ts b/tests/boundary/cli/jsonInputSize.test.ts
new file mode 100644
index 000000000..fce9412f2
--- /dev/null
+++ b/tests/boundary/cli/jsonInputSize.test.ts
@@ -0,0 +1,69 @@
+import { constants } from "node:buffer";
+import { open } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect } from "vitest";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+cliTest(
+  "preserves the runtime string limit through CLI and Evidence file inputs",
+  async ({ cli, processes }) => {
+    const root = await createTestTempDirectory("rea-json-string-limit-");
+    const input = join(root, "oversized.json");
+    const file = await open(input, "wx");
+    try {
+      // Sparse zero bytes are valid UTF-8. Decoded length exceeds the runtime
+      // string limit before JSON syntax can be inspected; no fixture is retained.
+      await file.truncate(constants.MAX_STRING_LENGTH + 1);
+    } finally {
+      await file.close();
+    }
+    const limits = {
+      input_path: input,
+      input_bytes: constants.MAX_STRING_LENGTH + 1,
+      max_string_code_units: constants.MAX_STRING_LENGTH,
+    };
+    // Run readers sequentially in owned child processes, releasing each large
+    // read buffer when its process exits instead of retaining it in Vitest.
+    const result = await cli.run({
+      arguments: ["trace-application-feature", input, "--json"],
+    });
+    expect(result.json).toMatchObject({
+      code: "resource_constraint",
+      category: "resource_constraint",
+      input_path: input,
+      input_reason: "too-large",
+      retryable: false,
+      remediation: { action: expect.stringContaining("re-analyze") },
+      details: {
+        operation: "trace-application-feature",
+        resource: "memory",
+        reported_limits: limits,
+      },
+    });
+    expect(result.exitCode).toBe(1);
+    expect(result.stderr).toBe("");
+
+    const evidence = await processes.run(process.execPath, [
+      "--input-type=module",
+      "-e",
+      `import { readJsonFile } from "./dist/application/JsonFiles.js";
+       import { projectAnalysisError } from "./dist/domain/analysisErrorProjection.js";
+       const result = await readJsonFile(process.argv[1]);
+       console.log(JSON.stringify(result.ok ? result : projectAnalysisError(result.error)));`,
+      input,
+    ]);
+    expect(JSON.parse(evidence.stdout)).toMatchObject({
+      code: "resource_constraint",
+      details: {
+        operation: "read_evidence_file",
+        resource: "memory",
+        reported_limits: limits,
+      },
+    });
+    expect(evidence.stderr).toBe("");
+    expect(evidence.exitCode).toBe(0);
+  },
+);
diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts
index 273168fdb..e550f88b8 100644
--- a/tests/boundary/filesystem/cliJsonInput.test.ts
+++ b/tests/boundary/filesystem/cliJsonInput.test.ts
@@ -1,6 +1,7 @@
 import { execFile } from "node:child_process";
 import { constants as bufferConstants } from "node:buffer";
 import {
+  appendFile,
   chmod,
   open,
   symlink,
@@ -119,8 +120,7 @@ describe("CLI JSON input", () => {
           },
         },
         remediation: {
-          action:
-            "Split the JSON into smaller inputs or rerun its producer on a smaller subset, then retry.",
+          action: expect.stringContaining("re-analyze a smaller selection"),
         },
       },
     });
@@ -137,6 +137,13 @@ describe("CLI JSON input", () => {
     if (typeof multibyteResult.value !== "string")
       throw new Error("Expected parsed JSON string");
     expect(multibyteResult.value.length).toBe(characterCount);
+
+    // Large-input streaming must flush and reject an incomplete UTF-8 suffix.
+    await appendFile(path, Buffer.from([0xc3]));
+    expect(await parseCliJsonInput(path, "test-input")).toMatchObject({
+      ok: false,
+      error: { input_path: path, input_reason: "invalid-json" },
+    });
   }, 20_000);
 
   it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => {

From e3bbb9ac453da8d15f3b32511180451613710616 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 03:10:50 +0800
Subject: [PATCH 068/189] refactor(javascript)!: share semantic evidence at
 fact construction

Intern shared provenance in a graph-scoped context registry while retaining exact locations on every fact. Semantic traces carry their referenced context subset, and portable graph validation rejects stale or dangling commitments.

BREAKING CHANGE: Semantic graph facts now store evidence context IDs and locations. Graph and semantic trace results require an inline evidence_contexts table.
---
 docs/javascript-application-workflows.md      |   9 +
 .../ReconstructionObligationCandidates.ts     |   7 +-
 .../JavaScriptSemanticGraphAsyncProjection.ts |  48 ++-
 .../JavaScriptSemanticGraphBuilder.ts         |  18 +-
 ...riptSemanticGraphChildProcessProjection.ts |  21 +-
 .../JavaScriptSemanticGraphConstruction.ts    |  84 ++--
 .../JavaScriptSemanticGraphDataProjection.ts  |  21 +-
 .../JavaScriptSemanticGraphEvidence.ts        |   5 +-
 ...criptSemanticGraphFingerprintProjection.ts |  47 ++-
 .../JavaScriptSemanticGraphFlowProjection.ts  |  56 +--
 ...JavaScriptSemanticGraphObjectProjection.ts |  21 +-
 ...vaScriptSemanticGraphResourceProjection.ts |  25 +-
 .../JavaScriptSemanticGraphResources.test.ts  |  15 +-
 .../JavaScriptSemanticGraphValueProjection.ts |  68 +--
 .../javascriptExportShapeComparisonExample.ts |  42 +-
 .../javascriptRuntimeReconciliationExample.ts |  32 +-
 src/domain/hopperErrors.ts                    |   1 -
 .../javascriptApplicationEvidenceSchemas.ts   |  13 +
 .../javascript/javascriptSemanticGraph.ts     | 187 ++++++++-
 .../javascriptSemanticGraphQuery.test.ts      | 397 +++++++++++++-----
 .../javascriptSemanticGraphSchemas.ts         |  38 +-
 .../javascriptSemanticGraphTraversal.test.ts  | 393 +++++++++++------
 .../javascript/javascriptSemanticQuery.ts     |   8 +
 .../javascriptSemanticQuerySchemas.ts         |   2 +
 .../mcp/applicationExportShapeMcp.test.ts     |  15 +-
 25 files changed, 1109 insertions(+), 464 deletions(-)

diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md
index 63be6935f..e7ae76acb 100644
--- a/docs/javascript-application-workflows.md
+++ b/docs/javascript-application-workflows.md
@@ -23,6 +23,15 @@ artifact digest and structural graph ID. Semantic tracing requires the semantic
 relation graph and reports when it is unavailable rather than treating missing
 data as an empty graph.
 
+The semantic graph wire format stores shared non-location provenance once in
+its required `evidence_contexts` table. Each node, relation, fingerprint, and
+unknown retains its exact `evidence.location` and names the owning context with
+`evidence.context_id`. This is a breaking representation change: consumers
+reading fields such as `evidence.authority` must look up the context by ID and
+combine its fields with the fact's location. Semantic trace results include the
+canonical context subset referenced by their returned facts, so those facts
+remain self-contained in the response.
+
 ## Feature tracing
 
 Select one literal seed kind: node ID, route, string, API, IPC channel, module,
diff --git a/src/application/ReconstructionObligationCandidates.ts b/src/application/ReconstructionObligationCandidates.ts
index 005f9b767..b01f88d7e 100644
--- a/src/application/ReconstructionObligationCandidates.ts
+++ b/src/application/ReconstructionObligationCandidates.ts
@@ -12,6 +12,7 @@ import type {
   ReconstructionObligation,
   ReviewedReconstructionObligation,
 } from "../domain/reconstructionObligationLedgerSchemas.js";
+import { resolveJavaScriptSemanticEvidence } from "../domain/javascript/javascriptSemanticGraph.js";
 import { parseApplicationGraphEvidence } from "./javascript/JavaScriptApplicationEvidenceGraph.js";
 import {
   applicationObligationPolicy,
@@ -111,6 +112,10 @@ const deriveApplicationCandidates = (
       for (const node of source.semanticGraph.nodes) {
         const candidatePolicy = semanticObligationPolicy(node.kind);
         if (candidatePolicy === undefined) continue;
+        const evidenceContext = resolveJavaScriptSemanticEvidence(
+          source.semanticGraph,
+          node.evidence,
+        );
         addCandidate(
           candidates,
           generatedCandidate({
@@ -125,7 +130,7 @@ const deriveApplicationCandidates = (
               graphReference(
                 evidence,
                 records,
-                node.evidence,
+                evidenceContext,
                 `${source.semanticGraph.graph_id}/node/${node.node_id}`,
               ),
             ],
diff --git a/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts b/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts
index bd638fc72..a8814281f 100644
--- a/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts
@@ -120,18 +120,21 @@ const addEventUnknown = (
 ): void => {
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: event.node_id,
-      family: "event",
-      relation_kinds: [relation],
-      reason: "ambiguous-target",
-      detail:
-        operation.eventName === null
-          ? `Dynamic ${operation.method} event name remains unresolved.`
-          : `Static ${operation.method} emitter identity is partial.`,
-      candidate_node_ids: [],
-      evidence: unknownSemanticEvidence(context.file, operation.location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: event.node_id,
+        family: "event",
+        relation_kinds: [relation],
+        reason: "ambiguous-target",
+        detail:
+          operation.eventName === null
+            ? `Dynamic ${operation.method} event name remains unresolved.`
+            : `Static ${operation.method} emitter identity is partial.`,
+        candidate_node_ids: [],
+        evidence: unknownSemanticEvidence(context.file, operation.location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
 
@@ -210,14 +213,17 @@ const projectTimerCancellation = (
   if (operation.resolution === "complete") return;
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: callSite?.node_id ?? null,
-      family: "timer",
-      relation_kinds: ["cancels-timer"],
-      reason: "ambiguous-target",
-      detail: `Static ${operation.method} handle resolution was ${operation.resolution}.`,
-      candidate_node_ids: [],
-      evidence: unknownSemanticEvidence(context.file, operation.location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: callSite?.node_id ?? null,
+        family: "timer",
+        relation_kinds: ["cancels-timer"],
+        reason: "ambiguous-target",
+        detail: `Static ${operation.method} handle resolution was ${operation.resolution}.`,
+        candidate_node_ids: [],
+        evidence: unknownSemanticEvidence(context.file, operation.location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
index 7736c1010..a951a7a55 100644
--- a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts
@@ -3,7 +3,10 @@ import {
   createImmutableJavaScriptSemanticGraphSteps,
   type JavaScriptSemanticGraph,
 } from "../../domain/javascript/javascriptSemanticGraph.js";
-import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
+import type {
+  JavaScriptSemanticFingerprint,
+  JavaScriptSemanticGraphNode,
+} from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 import {
   JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
   JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
@@ -141,7 +144,7 @@ export interface JavaScriptSemanticGraphProjection {
 export const createJavaScriptSemanticGraphProjection =
   (): JavaScriptSemanticGraphProjection => {
     const state = emptyState({ nodes: [] });
-    const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
+    const fingerprints: JavaScriptSemanticFingerprint[] = [];
     let truncatedFiles = 0;
     const projectSource = (
       file: JavaScriptArtifactFile,
@@ -178,6 +181,7 @@ export const createJavaScriptSemanticGraphProjection =
         root_artifact_sha256: rootArtifactSha256,
         application_graph_id: applicationGraph.graph_id,
         root_node_ids: [...state.roots],
+        evidence_contexts: state.evidenceContexts.contexts,
         nodes: [...state.nodes.values()],
         relations: [...state.relations.values()],
         fingerprints,
@@ -229,6 +233,7 @@ export const createJavaScriptSemanticGraphProjection =
       state.relations.clear();
       state.unknowns.clear();
       state.roots.clear();
+      state.evidenceContexts.clear();
       fingerprints.length = 0;
       return graph;
     };
@@ -253,7 +258,7 @@ const projectFile = (
   file: JavaScriptArtifactFile,
   ir: JavaScriptSemanticIr,
   state: BuilderState,
-): JavaScriptSemanticGraph["fingerprints"][number][] => {
+): JavaScriptSemanticFingerprint[] => {
   const moduleNode = retainNode(state, file, {
     kind: "module",
     roleKey: "module",
@@ -335,7 +340,12 @@ const projectFile = (
   projectSemanticResources(context);
   projectSemanticClosureCaptures(context);
   projectSemanticFrontiers(context);
-  return projectSemanticFunctionFingerprints(file, ir, callableNodes);
+  return projectSemanticFunctionFingerprints(
+    file,
+    ir,
+    callableNodes,
+    state.evidenceContexts,
+  );
 };
 
 const createReturnSiteNodes = (
diff --git a/src/application/javascript/JavaScriptSemanticGraphChildProcessProjection.ts b/src/application/javascript/JavaScriptSemanticGraphChildProcessProjection.ts
index 4a600d595..d7f44faaa 100644
--- a/src/application/javascript/JavaScriptSemanticGraphChildProcessProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphChildProcessProjection.ts
@@ -223,14 +223,17 @@ const addChildUnknown = (input: ChildUnknownInput): void => {
     input;
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: node?.node_id ?? null,
-      family: "child-process",
-      relation_kinds: relationKinds,
-      reason: "ambiguous-target",
-      detail,
-      candidate_node_ids: candidateNodeIds,
-      evidence: unknownSemanticEvidence(context.file, location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: node?.node_id ?? null,
+        family: "child-process",
+        relation_kinds: relationKinds,
+        reason: "ambiguous-target",
+        detail,
+        candidate_node_ids: candidateNodeIds,
+        evidence: unknownSemanticEvidence(context.file, location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphConstruction.ts b/src/application/javascript/JavaScriptSemanticGraphConstruction.ts
index 0b9ba9035..ebe27fe43 100644
--- a/src/application/javascript/JavaScriptSemanticGraphConstruction.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphConstruction.ts
@@ -4,6 +4,7 @@ import { javascriptDisplayText } from "../../domain/javascript/javascriptAstValu
 import {
   createJavaScriptSemanticGraphNode,
   createJavaScriptSemanticGraphRelation,
+  JavaScriptSemanticEvidenceContextRegistry,
   javaScriptSemanticNodeId,
 } from "../../domain/javascript/javascriptSemanticGraph.js";
 import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
@@ -25,6 +26,7 @@ export interface SemanticGraphProjectionState {
   readonly nodes: Map;
   readonly relations: Map;
   readonly unknowns: Map;
+  readonly evidenceContexts: JavaScriptSemanticEvidenceContextRegistry;
   readonly roots: Set;
   readonly applicationNodeIdsByLocation: ReadonlyMap;
   /**
@@ -76,6 +78,7 @@ export const createSemanticGraphProjectionState = (
     nodes: new Map(),
     relations: new Map(),
     unknowns: new Map(),
+    evidenceContexts: new JavaScriptSemanticEvidenceContextRegistry(),
     roots: new Set(),
     applicationNodeIdsByLocation: index.identifiers,
   };
@@ -109,20 +112,23 @@ export const constructSemanticGraphNode = (
   input: SemanticNodeConstructionInput,
   state: SemanticGraphProjectionState,
 ): JavaScriptSemanticGraphNode =>
-  createJavaScriptSemanticGraphNode({
-    kind: input.kind,
-    identity: {
-      artifact_sha256: file.sha256,
-      module_path: file.path,
-      source_range: input.location,
-      role_key: input.roleKey,
+  createJavaScriptSemanticGraphNode(
+    {
+      kind: input.kind,
+      identity: {
+        artifact_sha256: file.sha256,
+        module_path: file.path,
+        source_range: input.location,
+        role_key: input.roleKey,
+      },
+      function_node_id: input.functionNodeId,
+      application_node_ids: matchingApplicationNodeIds(file, input, state),
+      label: input.label === null ? null : javascriptDisplayText(input.label),
+      properties: input.properties ?? {},
+      evidence: observedSemanticEvidence(file, input.location),
     },
-    function_node_id: input.functionNodeId,
-    application_node_ids: matchingApplicationNodeIds(file, input, state),
-    label: input.label === null ? null : javascriptDisplayText(input.label),
-    properties: input.properties ?? {},
-    evidence: observedSemanticEvidence(file, input.location),
-  });
+    state.evidenceContexts,
+  );
 
 /** Reuse retained identities and reject exhausted budgets before allocation. */
 export const retainSemanticGraphNode = (
@@ -183,14 +189,21 @@ export const addSemanticGraphRelation = (
     input.source.node_id === input.target.node_id
   )
     return;
-  const value = createJavaScriptSemanticGraphRelation({
-    source_node_id: input.source.node_id,
-    target_node_id: input.target.node_id,
-    relation: input.relation,
-    resolution: input.resolution ?? "candidate",
-    properties: input.properties ?? {},
-    evidence: input.evidence ?? inferredSemanticEvidence(input.source),
-  });
+  const value = createJavaScriptSemanticGraphRelation(
+    {
+      source_node_id: input.source.node_id,
+      target_node_id: input.target.node_id,
+      relation: input.relation,
+      resolution: input.resolution ?? "candidate",
+      properties: input.properties ?? {},
+      evidence:
+        input.evidence ??
+        inferredSemanticEvidence(
+          state.evidenceContexts.resolve(input.source.evidence),
+        ),
+    },
+    state.evidenceContexts,
+  );
   if (state.relations.has(value.relation_id)) return;
   state.relations.set(value.relation_id, value);
 };
@@ -211,20 +224,23 @@ export const addSemanticFallbackRoot = (
 ): void => {
   const node = addSemanticGraphNode(
     state,
-    createJavaScriptSemanticGraphNode({
-      kind: "module",
-      identity: {
-        artifact_sha256: rootArtifactSha256,
-        module_path: "unknown-semantic-root",
-        source_range: null,
-        role_key: "artifact-root",
+    createJavaScriptSemanticGraphNode(
+      {
+        kind: "module",
+        identity: {
+          artifact_sha256: rootArtifactSha256,
+          module_path: "unknown-semantic-root",
+          source_range: null,
+          role_key: "artifact-root",
+        },
+        function_node_id: null,
+        application_node_ids: [],
+        label: "unavailable semantic root",
+        properties: {},
+        evidence: unavailableSemanticRootEvidence(rootArtifactSha256),
       },
-      function_node_id: null,
-      application_node_ids: [],
-      label: "unavailable semantic root",
-      properties: {},
-      evidence: unavailableSemanticRootEvidence(rootArtifactSha256),
-    }),
+      state.evidenceContexts,
+    ),
   );
   if (node !== null) state.roots.add(node.node_id);
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts b/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts
index b87bc6b3e..51efcd2ec 100644
--- a/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts
@@ -307,14 +307,17 @@ const addDataUnknown = (input: DataUnknownInput): void => {
   } = input;
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: node.node_id,
-      family,
-      relation_kinds: relationKinds,
-      reason: "ambiguous-target",
-      detail,
-      candidate_node_ids: candidateNodeIds,
-      evidence: unknownSemanticEvidence(context.file, location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: node.node_id,
+        family,
+        relation_kinds: relationKinds,
+        reason: "ambiguous-target",
+        detail,
+        candidate_node_ids: candidateNodeIds,
+        evidence: unknownSemanticEvidence(context.file, location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphEvidence.ts b/src/application/javascript/JavaScriptSemanticGraphEvidence.ts
index d80201593..d408170f7 100644
--- a/src/application/javascript/JavaScriptSemanticGraphEvidence.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphEvidence.ts
@@ -1,5 +1,4 @@
 import type { ApplicationGraphEvidence } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
-import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
 import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
 
@@ -44,9 +43,9 @@ export const observedSemanticEvidence = (
 
 /** Conservative static relationship evidence derived from one syntax node. */
 export const inferredSemanticEvidence = (
-  source: JavaScriptSemanticGraphNode,
+  source: ApplicationGraphEvidence,
 ): ApplicationGraphEvidence => ({
-  ...source.evidence,
+  ...source,
   authority: "static-relationship-inference",
   state: "inferred",
   confidence: "high",
diff --git a/src/application/javascript/JavaScriptSemanticGraphFingerprintProjection.ts b/src/application/javascript/JavaScriptSemanticGraphFingerprintProjection.ts
index 30d1506ed..10b7ab495 100644
--- a/src/application/javascript/JavaScriptSemanticGraphFingerprintProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphFingerprintProjection.ts
@@ -1,8 +1,11 @@
 import {
   createJavaScriptSemanticFingerprint,
-  type JavaScriptSemanticGraph,
+  type JavaScriptSemanticEvidenceContextRegistry,
 } from "../../domain/javascript/javascriptSemanticGraph.js";
-import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
+import type {
+  JavaScriptSemanticFingerprint,
+  JavaScriptSemanticGraphNode,
+} from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
 import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
 import { observedSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
@@ -12,28 +15,32 @@ export const projectSemanticFunctionFingerprints = (
   file: JavaScriptArtifactFile,
   ir: JavaScriptSemanticIr,
   callableNodes: ReadonlyMap,
-): JavaScriptSemanticGraph["fingerprints"][number][] =>
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
+): JavaScriptSemanticFingerprint[] =>
   ir.functionFingerprints.flatMap((fingerprint) => {
     const callable = callableNodes.get(fingerprint.callableId);
     if (callable === undefined) return [];
     return [
-      createJavaScriptSemanticFingerprint({
-        function_node_id: callable.node_id,
-        algorithm: "rea.javascript-semantic-function",
-        status: fingerprint.status,
-        components: {
-          parameter_arity: fingerprint.components.parameterArity,
-          normalized_ast_sha256: fingerprint.components.normalizedAstSha256,
-          control_flow_sha256: fingerprint.components.controlFlowSha256,
-          relation_shape_sha256: fingerprint.components.relationShapeSha256,
-          literal_set_sha256: fingerprint.components.literalSetSha256,
-          effects: fingerprint.components.effects,
+      createJavaScriptSemanticFingerprint(
+        {
+          function_node_id: callable.node_id,
+          algorithm: "rea.javascript-semantic-function",
+          status: fingerprint.status,
+          components: {
+            parameter_arity: fingerprint.components.parameterArity,
+            normalized_ast_sha256: fingerprint.components.normalizedAstSha256,
+            control_flow_sha256: fingerprint.components.controlFlowSha256,
+            relation_shape_sha256: fingerprint.components.relationShapeSha256,
+            literal_set_sha256: fingerprint.components.literalSetSha256,
+            effects: fingerprint.components.effects,
+          },
+          limitations: fingerprint.limitations,
+          evidence: observedSemanticEvidence(
+            file,
+            callable.identity.source_range,
+          ),
         },
-        limitations: fingerprint.limitations,
-        evidence: observedSemanticEvidence(
-          file,
-          callable.identity.source_range,
-        ),
-      }),
+        evidenceContexts,
+      ),
     ];
   });
diff --git a/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts b/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts
index 6195bbed3..be801ab86 100644
--- a/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts
@@ -179,18 +179,21 @@ const addPromiseUnknown = (
   const relation = operation.kind === "aggregate" ? "aggregates" : "chains";
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: promise.node_id,
-      family: "promise-ownership",
-      relation_kinds: [relation],
-      reason: "ambiguous-target",
-      detail: `Static ${operation.method} source resolution was ${operation.sourceResolution}.`,
-      candidate_node_ids: operation.sourcePromiseIds.flatMap((identifier) => {
-        const candidate = promiseNodes.get(identifier);
-        return candidate === undefined ? [] : [candidate.node_id];
-      }),
-      evidence: unknownSemanticEvidence(context.file, operation.location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: promise.node_id,
+        family: "promise-ownership",
+        relation_kinds: [relation],
+        reason: "ambiguous-target",
+        detail: `Static ${operation.method} source resolution was ${operation.sourceResolution}.`,
+        candidate_node_ids: operation.sourcePromiseIds.flatMap((identifier) => {
+          const candidate = promiseNodes.get(identifier);
+          return candidate === undefined ? [] : [candidate.node_id];
+        }),
+        evidence: unknownSemanticEvidence(context.file, operation.location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
 
@@ -254,19 +257,22 @@ export const projectSemanticFrontiers = (
         : frontier.kind === "dynamic-scope"
           ? (["reads", "writes"] as const)
           : (["reads-property", "writes-property"] as const);
-    const unknown = createJavaScriptSemanticGraphUnknown({
-      node_id:
-        frontier.callableId === null
-          ? context.moduleNode.node_id
-          : (context.callableNodes.get(frontier.callableId)?.node_id ??
-            context.moduleNode.node_id),
-      family,
-      relation_kinds: [...relationKinds],
-      reason: frontier.kind,
-      detail: frontier.reason,
-      candidate_node_ids: [],
-      evidence: unknownSemanticEvidence(context.file, frontier.location),
-    });
+    const unknown = createJavaScriptSemanticGraphUnknown(
+      {
+        node_id:
+          frontier.callableId === null
+            ? context.moduleNode.node_id
+            : (context.callableNodes.get(frontier.callableId)?.node_id ??
+              context.moduleNode.node_id),
+        family,
+        relation_kinds: [...relationKinds],
+        reason: frontier.kind,
+        detail: frontier.reason,
+        candidate_node_ids: [],
+        evidence: unknownSemanticEvidence(context.file, frontier.location),
+      },
+      context.state.evidenceContexts,
+    );
     addSemanticGraphUnknown(context.state, unknown);
   }
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts b/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts
index f4c94d21e..1b71b2784 100644
--- a/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts
@@ -168,14 +168,17 @@ const addObjectUnknown = (
   const relation = OBJECT_RELATIONS[operation.kind];
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: node?.node_id ?? null,
-      family: "object-flow",
-      relation_kinds: [relation],
-      reason: "ambiguous-target",
-      detail: `Static ${operation.kind} property ${operation.propertyPath === null ? "path is unresolved" : semanticPropertyPointer(operation.propertyPath)} has ${target.presence} presence; its receiver is ${target.receiverResolved ? "a retained container" : "unresolved or not a retained container"}; object identity is ${operation.resolution}.`,
-      candidate_node_ids: [],
-      evidence: unknownSemanticEvidence(context.file, operation.location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: node?.node_id ?? null,
+        family: "object-flow",
+        relation_kinds: [relation],
+        reason: "ambiguous-target",
+        detail: `Static ${operation.kind} property ${operation.propertyPath === null ? "path is unresolved" : semanticPropertyPointer(operation.propertyPath)} has ${target.presence} presence; its receiver is ${target.receiverResolved ? "a retained container" : "unresolved or not a retained container"}; object identity is ${operation.resolution}.`,
+        candidate_node_ids: [],
+        evidence: unknownSemanticEvidence(context.file, operation.location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts b/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts
index ffadc0448..7417eb4ba 100644
--- a/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphResourceProjection.ts
@@ -69,16 +69,19 @@ const projectRelease = (
   if (operation.resolution === "complete") return;
   addSemanticGraphUnknown(
     context.state,
-    createJavaScriptSemanticGraphUnknown({
-      node_id: callSite?.node_id ?? null,
-      family: "resource-lifecycle",
-      relation_kinds: ["releases"],
-      reason: "ambiguous-target",
-      detail: `Static ${operation.method} resource ownership is ambiguous.`,
-      candidate_node_ids: resources.map(
-        ({ node_id: identifier }) => identifier,
-      ),
-      evidence: unknownSemanticEvidence(context.file, operation.location),
-    }),
+    createJavaScriptSemanticGraphUnknown(
+      {
+        node_id: callSite?.node_id ?? null,
+        family: "resource-lifecycle",
+        relation_kinds: ["releases"],
+        reason: "ambiguous-target",
+        detail: `Static ${operation.method} resource ownership is ambiguous.`,
+        candidate_node_ids: resources.map(
+          ({ node_id: identifier }) => identifier,
+        ),
+        evidence: unknownSemanticEvidence(context.file, operation.location),
+      },
+      context.state.evidenceContexts,
+    ),
   );
 };
diff --git a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
index 6f7776011..afedb6f96 100644
--- a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts
@@ -4,6 +4,7 @@ import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.j
 import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
 import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
 import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
+import { resolveJavaScriptSemanticEvidence } from "../../domain/javascript/javascriptSemanticGraph.js";
 import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
 
 const SHA256 = "a".repeat(64);
@@ -335,11 +336,15 @@ it("uses unavailable evidence when no source produced semantic IR", () => {
     applicationGraph: { graph_id: GRAPH_ID, nodes: [] },
     analysis: emptyAnalysis(),
   });
-  expect(graph.nodes[0]?.evidence).toMatchObject({
-    authority: "unknown",
-    state: "unavailable",
-    location: { available: false, reason: "not-observed" },
-  });
+  const root = graph.nodes[0];
+  if (root === undefined) throw new Error("Expected unavailable semantic root");
+  expect(resolveJavaScriptSemanticEvidence(graph, root.evidence)).toMatchObject(
+    {
+      authority: "unknown",
+      state: "unavailable",
+      location: { available: false, reason: "not-observed" },
+    },
+  );
 });
 
 const emptyAnalysis = (): JavaScriptArtifactAnalysis => ({
diff --git a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
index bcc9db294..b8002fcd0 100644
--- a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
+++ b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts
@@ -96,20 +96,23 @@ const projectValue = (input: ValueProjectionInput): void => {
     if (container.coverage.status === "partial")
       addSemanticGraphUnknown(
         context.state,
-        createJavaScriptSemanticGraphUnknown({
-          node_id: target.node_id,
-          family: "object-flow",
-          relation_kinds: ["writes-property"],
-          reason: "ambiguous-target",
-          detail: `Initializer container has unknown ${
-            value.status === "object" ? "properties" : "items"
-          }${container.coverage.omitted === null ? " with an unknown omitted count" : `; ${container.coverage.omitted} omitted`}.`,
-          candidate_node_ids: [target.node_id],
-          evidence: unknownSemanticEvidence(
-            context.file,
-            binding.definitions[0]?.location ?? null,
-          ),
-        }),
+        createJavaScriptSemanticGraphUnknown(
+          {
+            node_id: target.node_id,
+            family: "object-flow",
+            relation_kinds: ["writes-property"],
+            reason: "ambiguous-target",
+            detail: `Initializer container has unknown ${
+              value.status === "object" ? "properties" : "items"
+            }${container.coverage.omitted === null ? " with an unknown omitted count" : `; ${container.coverage.omitted} omitted`}.`,
+            candidate_node_ids: [target.node_id],
+            evidence: unknownSemanticEvidence(
+              context.file,
+              binding.definitions[0]?.location ?? null,
+            ),
+          },
+          context.state.evidenceContexts,
+        ),
       );
   } else if (
     value.status === "unknown" ||
@@ -120,24 +123,27 @@ const projectValue = (input: ValueProjectionInput): void => {
     const evidence = observedSemanticEvidence(context.file, location);
     addSemanticGraphUnknown(
       context.state,
-      createJavaScriptSemanticGraphUnknown({
-        node_id: target.node_id,
-        family: "data-flow",
-        relation_kinds: ["defines"],
-        reason:
-          value.resourceLimit === undefined
-            ? "unknown-value"
-            : "resource-limit",
-        detail: `${value.reason} Unknown value at ${role}.`,
-        candidate_node_ids: [target.node_id],
-        evidence: {
-          ...evidence,
-          authority: "unknown",
-          state: "unknown",
-          confidence: "unknown",
-          limitations: [value.reason],
+      createJavaScriptSemanticGraphUnknown(
+        {
+          node_id: target.node_id,
+          family: "data-flow",
+          relation_kinds: ["defines"],
+          reason:
+            value.resourceLimit === undefined
+              ? "unknown-value"
+              : "resource-limit",
+          detail: `${value.reason} Unknown value at ${role}.`,
+          candidate_node_ids: [target.node_id],
+          evidence: {
+            ...evidence,
+            authority: "unknown",
+            state: "unknown",
+            confidence: "unknown",
+            limitations: [value.reason],
+          },
         },
-      }),
+        context.state.evidenceContexts,
+      ),
     );
   }
 };
diff --git a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
index 221367859..65464336d 100644
--- a/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
+++ b/src/contracts/javascript/javascriptExportShapeComparisonExample.ts
@@ -13,6 +13,7 @@ import {
 import {
   createJavaScriptSemanticGraph,
   createJavaScriptSemanticGraphNode,
+  JavaScriptSemanticEvidenceContextRegistry,
 } from "../../domain/javascript/javascriptSemanticGraph.js";
 import { JAVASCRIPT_SEMANTIC_RELATION_FAMILIES } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 import { javascriptApplicationAnalysisResultSchema } from "../../domain/javascript/javascriptApplicationAnalysis.js";
@@ -184,30 +185,35 @@ const exampleEvidence = (property: "count" | "total") => {
     coverage: partialApplicationCoverage([], null),
     limitations,
   });
-  const module = createJavaScriptSemanticGraphNode({
-    kind: "module",
-    identity: {
-      artifact_sha256: artifact.sha256,
-      module_path: modulePath,
-      source_range: null,
-      role_key: "example-module",
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const module = createJavaScriptSemanticGraphNode(
+    {
+      kind: "module",
+      identity: {
+        artifact_sha256: artifact.sha256,
+        module_path: modulePath,
+        source_range: null,
+        role_key: "example-module",
+      },
+      function_node_id: null,
+      application_node_ids: [exported.node_id],
+      label: modulePath,
+      properties: {},
+      evidence: {
+        ...evidence,
+        authority: "ast-static-analysis",
+        state: "observed",
+        confidence: "exact",
+      },
     },
-    function_node_id: null,
-    application_node_ids: [exported.node_id],
-    label: modulePath,
-    properties: {},
-    evidence: {
-      ...evidence,
-      authority: "ast-static-analysis",
-      state: "observed",
-      confidence: "exact",
-    },
-  });
+    evidenceContexts,
+  );
   const semanticGraph = createJavaScriptSemanticGraph({
     schema: "JavaScriptSemanticRelationGraph",
     root_artifact_sha256: metadata.root_artifact_sha256,
     application_graph_id: graph.graph_id,
     root_node_ids: [module.node_id],
+    evidence_contexts: evidenceContexts.contexts,
     nodes: [module],
     relations: [],
     fingerprints: [],
diff --git a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
index c6eacc8a9..4be73fab7 100644
--- a/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
+++ b/src/contracts/javascript/javascriptRuntimeReconciliationExample.ts
@@ -7,6 +7,7 @@ import { createWebTextArtifact } from "../../domain/webContentArtifact.js";
 import {
   createJavaScriptSemanticGraph,
   createJavaScriptSemanticGraphNode,
+  JavaScriptSemanticEvidenceContextRegistry,
 } from "../../domain/javascript/javascriptSemanticGraph.js";
 import { JAVASCRIPT_SEMANTIC_RELATION_FAMILIES } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
 
@@ -70,25 +71,30 @@ const graph = createJavaScriptApplicationGraph({
   coverage: completeCoverage,
   limitations: [],
 });
-const semanticNode = createJavaScriptSemanticGraphNode({
-  kind: "module",
-  identity: {
-    artifact_sha256: applicationSha256,
-    module_path: "renderer.js",
-    source_range: null,
-    role_key: "example-module",
+const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+const semanticNode = createJavaScriptSemanticGraphNode(
+  {
+    kind: "module",
+    identity: {
+      artifact_sha256: applicationSha256,
+      module_path: "renderer.js",
+      source_range: null,
+      role_key: "example-module",
+    },
+    function_node_id: null,
+    application_node_ids: [asset.node_id],
+    label: "renderer.js",
+    properties: {},
+    evidence: graphEvidence,
   },
-  function_node_id: null,
-  application_node_ids: [asset.node_id],
-  label: "renderer.js",
-  properties: {},
-  evidence: graphEvidence,
-});
+  evidenceContexts,
+);
 const semanticGraph = createJavaScriptSemanticGraph({
   schema: "JavaScriptSemanticRelationGraph",
   root_artifact_sha256: applicationSha256,
   application_graph_id: graph.graph_id,
   root_node_ids: [semanticNode.node_id],
+  evidence_contexts: evidenceContexts.contexts,
   nodes: [semanticNode],
   relations: [],
   fingerprints: [],
diff --git a/src/domain/hopperErrors.ts b/src/domain/hopperErrors.ts
index 68c5b9ee4..8cb849081 100644
--- a/src/domain/hopperErrors.ts
+++ b/src/domain/hopperErrors.ts
@@ -5,7 +5,6 @@ import type {
 } from "./providerOperationHealth.js";
 import {
   hopperStartupFailure,
-  type HopperStartupDiagnostic,
   type HopperStartupFailureCode,
   type HopperStartupFailureDiagnostic,
 } from "./hopperStartupFailure.js";
diff --git a/src/domain/javascript/javascriptApplicationEvidenceSchemas.ts b/src/domain/javascript/javascriptApplicationEvidenceSchemas.ts
index a53db2a74..65bce595b 100644
--- a/src/domain/javascript/javascriptApplicationEvidenceSchemas.ts
+++ b/src/domain/javascript/javascriptApplicationEvidenceSchemas.ts
@@ -269,6 +269,14 @@ const applicationGraphEvidenceBaseSchema = z.strictObject({
   evidence_ids: z.array(prefixedDigestSchema("ev")),
 });
 
+/** Shared provenance fields apart from the fact-specific evidence location. */
+export const applicationGraphEvidenceContextSchema =
+  applicationGraphEvidenceBaseSchema.omit({ location: true });
+
+/** Exact coordinates retained on each graph fact. */
+export const applicationGraphEvidenceLocationSchema =
+  applicationLocationReferenceSchema;
+
 type EvidenceValue = z.infer;
 
 const checkAuthorityState = (
@@ -476,6 +484,11 @@ export type ApplicationGraphEvidence = z.infer<
   typeof applicationGraphEvidenceSchema
 >;
 
+/** Provenance shared by facts with the same non-location evidence. */
+export type ApplicationGraphEvidenceContext = z.infer<
+  typeof applicationGraphEvidenceContextSchema
+>;
+
 /** Explicit stable identity strategy for one application entity. */
 export type ApplicationNodeIdentity = z.infer<
   typeof applicationNodeIdentitySchema
diff --git a/src/domain/javascript/javascriptSemanticGraph.ts b/src/domain/javascript/javascriptSemanticGraph.ts
index 032a2802c..e6cf1d530 100644
--- a/src/domain/javascript/javascriptSemanticGraph.ts
+++ b/src/domain/javascript/javascriptSemanticGraph.ts
@@ -6,7 +6,11 @@ import { uniqueSorted } from "../canonicalOrdering.js";
 import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
 import { canonicalJsonDigestSteps } from "../canonicalJsonDigestSteps.js";
 import { freezeOwnedJsonSnapshotSteps } from "../immutableJson.js";
-import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
+import type {
+  ApplicationGraphEvidence,
+  ApplicationGraphEvidenceContext,
+} from "./javascriptApplicationEvidenceSchemas.js";
+import { applicationGraphEvidenceSchema } from "./javascriptApplicationEvidenceSchemas.js";
 import {
   JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
   JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
@@ -23,6 +27,10 @@ import {
   type JavaScriptSemanticGraphInput,
   type JavaScriptSemanticGraphNode,
   type JavaScriptSemanticGraphRelation,
+  type JavaScriptSemanticGraphUnknown,
+  type JavaScriptSemanticFingerprint,
+  type JavaScriptSemanticEvidenceContext,
+  type JavaScriptSemanticEvidenceReference,
 } from "./javascriptSemanticGraphSchemas.js";
 
 const normalizeEvidence = (
@@ -42,6 +50,60 @@ const normalizeEvidence = (
   evidence_ids: uniqueSorted(evidence.evidence_ids),
 });
 
+const evidenceContextId = (context: ApplicationGraphEvidenceContext): string =>
+  `jsrg_evidence_${digestCanonicalValue(context, "JavaScript semantic evidence context")}`;
+
+/** Graph-scoped owner for canonical provenance shared by semantic facts. */
+export class JavaScriptSemanticEvidenceContextRegistry {
+  readonly #contexts = new Map();
+
+  /** Intern normalized non-location provenance at fact construction. */
+  intern(
+    evidence: ApplicationGraphEvidence,
+  ): JavaScriptSemanticEvidenceReference {
+    const normalized = normalizeEvidence(evidence);
+    const { location, ...context } = normalized;
+    const contextId = evidenceContextId(context);
+    const row = { ...context, context_id: contextId };
+    const existing = this.#contexts.get(contextId);
+    if (
+      existing !== undefined &&
+      canonicalJson(existing, "JavaScript semantic graph") !==
+        canonicalJson(row, "JavaScript semantic graph")
+    )
+      throw new TypeError(
+        "JavaScript semantic evidence context digest collision",
+      );
+    this.#contexts.set(contextId, row);
+    return { context_id: contextId, location };
+  }
+
+  /** Resolve one already interned fact reference for derived evidence. */
+  resolve(
+    reference: JavaScriptSemanticEvidenceReference,
+  ): ApplicationGraphEvidence {
+    const context = this.#contexts.get(reference.context_id);
+    if (context === undefined)
+      throw new TypeError(
+        "Semantic evidence reference names an absent context",
+      );
+    const { context_id: _contextId, ...evidenceContext } = context;
+    return { ...evidenceContext, location: reference.location };
+  }
+
+  /** Return the deterministic context table owned by this graph projection. */
+  get contexts(): JavaScriptSemanticEvidenceContext[] {
+    return [...this.#contexts.values()].sort((left, right) =>
+      compareUnicodeCodePoints(left.context_id, right.context_id),
+    );
+  }
+
+  /** Release interned contexts after the owning graph is finalized. */
+  clear(): void {
+    this.#contexts.clear();
+  }
+}
+
 /** Derive a semantic node ID from its kind and exact artifact identity. */
 export const javaScriptSemanticNodeId = (
   node: Pick,
@@ -51,12 +113,13 @@ export const javaScriptSemanticNodeId = (
 /** Normalize one semantic entity and derive its artifact-version identifier. */
 export const createJavaScriptSemanticGraphNode = (
   input: unknown,
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
 ): JavaScriptSemanticGraphNode => {
   const parsed = javaScriptSemanticNodeInputSchema.parse(input);
   const semantic = {
     ...parsed,
     application_node_ids: uniqueSorted(parsed.application_node_ids),
-    evidence: normalizeEvidence(parsed.evidence),
+    evidence: evidenceContexts.intern(parsed.evidence),
     identifier_strategy: {
       strategy: "semantic-content-sha256" as const,
       stability: "artifact-version" as const,
@@ -71,11 +134,12 @@ export const createJavaScriptSemanticGraphNode = (
 /** Normalize one semantic relationship and derive its exact identifier. */
 export const createJavaScriptSemanticGraphRelation = (
   input: unknown,
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
 ): JavaScriptSemanticGraphRelation => {
   const parsed = javaScriptSemanticRelationInputSchema.parse(input);
   const semantic = {
     ...parsed,
-    evidence: normalizeEvidence(parsed.evidence),
+    evidence: evidenceContexts.intern(parsed.evidence),
     identifier_strategy: {
       strategy: "semantic-content-sha256" as const,
       stability: "relationship-exact" as const,
@@ -88,13 +152,16 @@ export const createJavaScriptSemanticGraphRelation = (
 };
 
 /** Normalize one unresolved semantic frontier and derive its identifier. */
-export const createJavaScriptSemanticGraphUnknown = (input: unknown) => {
+export const createJavaScriptSemanticGraphUnknown = (
+  input: unknown,
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
+): JavaScriptSemanticGraphUnknown => {
   const parsed = javaScriptSemanticUnknownInputSchema.parse(input);
   const semantic = {
     ...parsed,
     relation_kinds: uniqueSorted(parsed.relation_kinds),
     candidate_node_ids: uniqueSorted(parsed.candidate_node_ids),
-    evidence: normalizeEvidence(parsed.evidence),
+    evidence: evidenceContexts.intern(parsed.evidence),
   };
   return javaScriptSemanticUnknownSchema.parse({
     ...semantic,
@@ -103,7 +170,10 @@ export const createJavaScriptSemanticGraphUnknown = (input: unknown) => {
 };
 
 /** Normalize one function fingerprint and derive its component commitment. */
-export const createJavaScriptSemanticFingerprint = (input: unknown) => {
+export const createJavaScriptSemanticFingerprint = (
+  input: unknown,
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
+): JavaScriptSemanticFingerprint => {
   const parsed = javaScriptSemanticFingerprintInputSchema.parse(input);
   const semantic = {
     ...parsed,
@@ -112,7 +182,7 @@ export const createJavaScriptSemanticFingerprint = (input: unknown) => {
       effects: uniqueSorted(parsed.components.effects),
     },
     limitations: uniqueSorted(parsed.limitations),
-    evidence: normalizeEvidence(parsed.evidence),
+    evidence: evidenceContexts.intern(parsed.evidence),
   };
   const fingerprintSha256 = digestCanonicalValue(
     semantic.components,
@@ -252,6 +322,12 @@ const checkCanonicalOrder = (
     "Root nodes",
     context,
   );
+  sortedUniqueIssue(
+    graph.evidence_contexts.map(({ context_id }) => context_id),
+    ["evidence_contexts"],
+    "Evidence contexts",
+    context,
+  );
   sortedUniqueIssue(
     graph.nodes.map(({ node_id }) => node_id),
     ["nodes"],
@@ -279,6 +355,66 @@ const checkCanonicalOrder = (
   sortedUniqueIssue(graph.limitations, ["limitations"], "Limitations", context);
 };
 
+function* checkEvidenceContextReferencesSteps(
+  graph: GraphRecord,
+  context: GraphIssueReporter,
+): Generator {
+  const contexts = new Map(
+    graph.evidence_contexts.map((value) => [value.context_id, value]),
+  );
+  const referenced = new Set();
+  const validateReferences = function* (
+    entities: readonly { evidence: JavaScriptSemanticEvidenceReference }[],
+    entityKind: "nodes" | "relations" | "unknowns" | "fingerprints",
+  ): Generator {
+    for (const [index, { evidence }] of entities.entries()) {
+      if (index % 256 === 0) yield;
+      referenced.add(evidence.context_id);
+      const evidenceContext = contexts.get(evidence.context_id);
+      if (evidenceContext === undefined) {
+        context.addIssue({
+          code: "custom",
+          path: [entityKind, index, "evidence", "context_id"],
+          message: "Evidence reference names an absent context",
+        });
+        continue;
+      }
+      const { context_id: _contextId, ...evidenceValue } = evidenceContext;
+      if (
+        !applicationGraphEvidenceSchema.safeParse({
+          ...evidenceValue,
+          location: evidence.location,
+        }).success
+      )
+        context.addIssue({
+          code: "custom",
+          path: [entityKind, index, "evidence"],
+          message: "Evidence context is incompatible with its fact location",
+        });
+    }
+  };
+  yield* validateReferences(graph.nodes, "nodes");
+  yield* validateReferences(graph.relations, "relations");
+  yield* validateReferences(graph.unknowns, "unknowns");
+  yield* validateReferences(graph.fingerprints, "fingerprints");
+  for (const [index, evidenceContext] of graph.evidence_contexts.entries()) {
+    if (index % 256 === 0) yield;
+    const { context_id: identifier, ...value } = evidenceContext;
+    if (identifier !== evidenceContextId(value))
+      context.addIssue({
+        code: "custom",
+        path: ["evidence_contexts", index, "context_id"],
+        message: "Evidence context identifier is stale",
+      });
+    if (!referenced.has(identifier))
+      context.addIssue({
+        code: "custom",
+        path: ["evidence_contexts", index],
+        message: "Evidence context is not referenced by a graph fact",
+      });
+  }
+}
+
 function* checkNodesSteps(
   graph: GraphRecord,
   nodes: ReadonlyMap,
@@ -323,6 +459,7 @@ function* checkRootsSteps(
 function* checkRelationsSteps(
   graph: GraphRecord,
   nodes: ReadonlyMap,
+  evidenceContexts: ReadonlyMap,
   context: GraphIssueReporter,
 ): Generator {
   for (const [index, relation] of graph.relations.entries()) {
@@ -355,7 +492,7 @@ function* checkRelationsSteps(
       });
     if (
       relation.resolution === "candidate" &&
-      relation.evidence.state === "observed"
+      evidenceContexts.get(relation.evidence.context_id)?.state === "observed"
     )
       context.addIssue({
         code: "custom",
@@ -368,6 +505,7 @@ function* checkRelationsSteps(
 function* checkUnknownsSteps(
   graph: GraphRecord,
   nodes: ReadonlyMap,
+  evidenceContexts: ReadonlyMap,
   context: GraphIssueReporter,
 ): Generator {
   for (const [index, unknown] of graph.unknowns.entries()) {
@@ -405,7 +543,10 @@ function* checkUnknownsSteps(
         path: ["unknowns", index, "relation_kinds"],
         message: "Unknown relation kinds must belong to their declared family",
       });
-    if (!["unknown", "unavailable"].includes(unknown.evidence.state))
+    const evidenceState = evidenceContexts.get(
+      unknown.evidence.context_id,
+    )?.state;
+    if (evidenceState !== "unknown" && evidenceState !== "unavailable")
       context.addIssue({
         code: "custom",
         path: ["unknowns", index, "evidence", "state"],
@@ -485,6 +626,13 @@ function* checkGraphContentSteps(
   context: GraphIssueReporter,
 ): Generator {
   checkCanonicalOrder(graph, context);
+  yield* checkEvidenceContextReferencesSteps(graph, context);
+  const evidenceContexts = new Map(
+    graph.evidence_contexts.map((evidenceContext) => [
+      evidenceContext.context_id,
+      evidenceContext,
+    ]),
+  );
   const nodes = new Map();
   for (const [index, node] of graph.nodes.entries()) {
     if (index % 256 === 0) yield;
@@ -492,8 +640,8 @@ function* checkGraphContentSteps(
   }
   yield* checkNodesSteps(graph, nodes, context);
   yield* checkRootsSteps(graph, nodes, context);
-  yield* checkRelationsSteps(graph, nodes, context);
-  yield* checkUnknownsSteps(graph, nodes, context);
+  yield* checkRelationsSteps(graph, nodes, evidenceContexts, context);
+  yield* checkUnknownsSteps(graph, nodes, evidenceContexts, context);
   checkUnknownReferences(graph, context);
   yield* checkFingerprintsSteps(graph, nodes, context);
   yield* checkCoverageSteps(graph, context);
@@ -538,11 +686,28 @@ export type JavaScriptSemanticGraph = z.infer<
   typeof javaScriptSemanticGraphSchema
 >;
 
+/** Resolve one fact's compact provenance without changing its stored shape. */
+export const resolveJavaScriptSemanticEvidence = (
+  graph: Pick,
+  reference: JavaScriptSemanticEvidenceReference,
+): ApplicationGraphEvidence => {
+  const context = graph.evidence_contexts.find(
+    ({ context_id }) => context_id === reference.context_id,
+  );
+  if (context === undefined)
+    throw new TypeError("Semantic evidence reference names an absent context");
+  const { context_id: _contextId, ...evidenceContext } = context;
+  return { ...evidenceContext, location: reference.location };
+};
+
 const normalizeGraphInput = (
   parsed: JavaScriptSemanticGraphInput,
 ): JavaScriptSemanticGraphInput => ({
   ...parsed,
   root_node_ids: uniqueSorted(parsed.root_node_ids),
+  evidence_contexts: [...parsed.evidence_contexts].sort((left, right) =>
+    compareUnicodeCodePoints(left.context_id, right.context_id),
+  ),
   nodes: [...parsed.nodes].sort((left, right) =>
     compareUnicodeCodePoints(left.node_id, right.node_id),
   ),
diff --git a/src/domain/javascript/javascriptSemanticGraphQuery.test.ts b/src/domain/javascript/javascriptSemanticGraphQuery.test.ts
index ba39bcf70..ddf3015f0 100644
--- a/src/domain/javascript/javascriptSemanticGraphQuery.test.ts
+++ b/src/domain/javascript/javascriptSemanticGraphQuery.test.ts
@@ -16,6 +16,9 @@ import {
   createJavaScriptSemanticGraphUnknown,
   createImmutableJavaScriptSemanticGraphSteps,
   isValidatedImmutableJavaScriptSemanticGraph,
+  JavaScriptSemanticEvidenceContextRegistry,
+  javaScriptSemanticGraphSchema,
+  resolveJavaScriptSemanticEvidence,
   type JavaScriptSemanticGraph,
 } from "./javascriptSemanticGraph.js";
 import type { JavaScriptSemanticGraphNode } from "./javascriptSemanticGraphSchemas.js";
@@ -100,80 +103,111 @@ const node = (
   kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
   role: string,
   properties: Record = {},
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
   options: {
     readonly functionNodeId?: string | null;
     readonly modulePath?: string;
   } = {},
 ): JavaScriptSemanticGraphNode =>
-  createJavaScriptSemanticGraphNode({
-    kind,
-    identity: {
-      artifact_sha256: SHA,
-      module_path: options.modulePath ?? "bundle.js",
-      source_range: {
-        start: { line: 1, column: role.length },
-        end: { line: 1, column: role.length + 1 },
+  createJavaScriptSemanticGraphNode(
+    {
+      kind,
+      identity: {
+        artifact_sha256: SHA,
+        module_path: options.modulePath ?? "bundle.js",
+        source_range: {
+          start: { line: 1, column: role.length },
+          end: { line: 1, column: role.length + 1 },
+        },
+        role_key: role,
       },
-      role_key: role,
+      function_node_id: options.functionNodeId ?? null,
+      application_node_ids: [],
+      label: role,
+      properties,
+      evidence: evidence(),
     },
-    function_node_id: options.functionNodeId ?? null,
-    application_node_ids: [],
-    label: role,
-    properties,
-    evidence: evidence(),
-  });
+    evidenceContexts,
+  );
 
 it("accepts semantic module paths longer than the former schema ceiling", () => {
   const modulePath = `${"segment/".repeat(600)}entry.js`;
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
   expect(
-    node("module", "long-path", {}, { modulePath }).identity.module_path,
+    node("module", "long-path", {}, evidenceContexts, { modulePath }).identity
+      .module_path,
   ).toBe(modulePath);
 });
 
-const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
-  const module = node("module", "module");
-  const literal = node("literal", "literal", { value: "TOKEN" });
-  const binding = node("binding", "binding");
-  const callable = node("function", "function");
-  const request = node("request", "request", {
-    endpoint: "https://example.invalid/v1",
-  });
+const fixtureInput = (withUnknown = false): JavaScriptSemanticGraphInput => {
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const module = node("module", "module", {}, evidenceContexts);
+  const literal = node(
+    "literal",
+    "literal",
+    { value: "TOKEN" },
+    evidenceContexts,
+  );
+  const binding = node("binding", "binding", {}, evidenceContexts);
+  const callable = node("function", "function", {}, evidenceContexts);
+  const request = node(
+    "request",
+    "request",
+    {
+      endpoint: "https://example.invalid/v1",
+    },
+    evidenceContexts,
+  );
   const relations = [
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: literal.node_id,
-      target_node_id: binding.node_id,
-      relation: "defines",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: binding.node_id,
-      target_node_id: callable.node_id,
-      relation: "captures",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: callable.node_id,
-      target_node_id: request.node_id,
-      relation: "constructs-request",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: literal.node_id,
+        target_node_id: binding.node_id,
+        relation: "defines",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: binding.node_id,
+        target_node_id: callable.node_id,
+        relation: "captures",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: callable.node_id,
+        target_node_id: request.node_id,
+        relation: "constructs-request",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
   ];
-  const dynamic = createJavaScriptSemanticGraphUnknown({
-    node_id: callable.node_id,
-    family: "call-flow",
-    relation_kinds: ["calls"],
-    reason: "dynamic-call",
-    detail: "Computed callee is unresolved.",
-    candidate_node_ids: [],
-    evidence: unknownEvidence(),
-  });
-  const unknowns = withUnknown ? [dynamic] : [];
+  const dynamic = withUnknown
+    ? createJavaScriptSemanticGraphUnknown(
+        {
+          node_id: callable.node_id,
+          family: "call-flow",
+          relation_kinds: ["calls"],
+          reason: "dynamic-call",
+          detail: "Computed callee is unresolved.",
+          candidate_node_ids: [],
+          evidence: unknownEvidence(),
+        },
+        evidenceContexts,
+      )
+    : null;
+  const unknowns = dynamic === null ? [] : [dynamic];
   const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
     (family) => ({
       family,
@@ -190,29 +224,33 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
       ).length,
       omitted_relations: withUnknown && family === "call-flow" ? null : 0,
       unknown_ids:
-        withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
+        dynamic !== null && family === "call-flow" ? [dynamic.unknown_id] : [],
     }),
   );
-  const fingerprint = createJavaScriptSemanticFingerprint({
-    function_node_id: callable.node_id,
-    algorithm: "rea.javascript-semantic-function",
-    status: "complete",
-    components: {
-      parameter_arity: 0,
-      normalized_ast_sha256: "1".repeat(64),
-      control_flow_sha256: "2".repeat(64),
-      relation_shape_sha256: "3".repeat(64),
-      literal_set_sha256: "4".repeat(64),
-      effects: ["network"],
+  const fingerprint = createJavaScriptSemanticFingerprint(
+    {
+      function_node_id: callable.node_id,
+      algorithm: "rea.javascript-semantic-function",
+      status: "complete",
+      components: {
+        parameter_arity: 0,
+        normalized_ast_sha256: "1".repeat(64),
+        control_flow_sha256: "2".repeat(64),
+        relation_shape_sha256: "3".repeat(64),
+        literal_set_sha256: "4".repeat(64),
+        effects: ["network"],
+      },
+      limitations: [],
+      evidence: evidence("inferred"),
     },
-    limitations: [],
-    evidence: evidence("inferred"),
-  });
-  return createJavaScriptSemanticGraph({
+    evidenceContexts,
+  );
+  return {
     schema: "JavaScriptSemanticRelationGraph",
     root_artifact_sha256: SHA,
     application_graph_id: JAG_ID,
     root_node_ids: [module.node_id],
+    evidence_contexts: evidenceContexts.contexts,
     nodes: [request, callable, binding, literal, module],
     relations,
     fingerprints: [fingerprint],
@@ -226,7 +264,24 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
       families: coverageFamilies,
     },
     limitations: withUnknown ? ["Dynamic call target remains unknown."] : [],
-  });
+  };
+};
+
+const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph =>
+  createJavaScriptSemanticGraph(fixtureInput(withUnknown));
+
+const registryForGraph = (
+  graph: JavaScriptSemanticGraph,
+): JavaScriptSemanticEvidenceContextRegistry => {
+  const registry = new JavaScriptSemanticEvidenceContextRegistry();
+  for (const { evidence: reference } of [
+    ...graph.nodes,
+    ...graph.relations,
+    ...graph.unknowns,
+    ...graph.fingerprints,
+  ])
+    registry.intern(resolveJavaScriptSemanticEvidence(graph, reference));
+  return registry;
 };
 
 it("defines every required relation family and canonicalizes records", () => {
@@ -247,7 +302,6 @@ it("defines every required relation family and canonicalizes records", () => {
 
 it("rejects stale identities, dangling endpoints, and incomplete coverage claims", () => {
   const graph = fixtureGraph();
-  const { graph_id: _graphId, ...graphInput } = graph;
   expect(() =>
     parseJavaScriptSemanticGraph({
       ...graph,
@@ -256,10 +310,10 @@ it("rejects stale identities, dangling endpoints, and incomplete coverage claims
   ).toThrow();
   expect(() =>
     createJavaScriptSemanticGraph({
-      ...graphInput,
+      ...fixtureInput(),
       relations: [
         {
-          ...graph.relations[0],
+          ...fixtureInput().relations[0],
           target_node_id: `jsrg_node_${"f".repeat(64)}`,
         },
       ],
@@ -267,27 +321,174 @@ it("rejects stale identities, dangling endpoints, and incomplete coverage claims
   ).toThrow();
   expect(() =>
     createJavaScriptSemanticGraph({
-      ...graphInput,
-      coverage: { ...graph.coverage, omitted_nodes: 1 },
+      ...fixtureInput(),
+      coverage: { ...fixtureInput().coverage, omitted_nodes: 1 },
     }),
   ).toThrow(/Complete graph coverage/u);
-  const graphWithUnknown = fixtureGraph(true);
-  const { graph_id: _unknownGraphId, ...unknownGraphInput } = graphWithUnknown;
-  const originalUnknown = graphWithUnknown.unknowns[0];
+  const unknownGraphInput = fixtureInput(true);
+  const originalUnknown = unknownGraphInput.unknowns[0];
   if (originalUnknown === undefined)
     throw new Error("Expected unknown frontier");
   const { unknown_id: _unknownId, ...unknownInput } = originalUnknown;
-  expect(() =>
-    createJavaScriptSemanticGraph({
-      ...unknownGraphInput,
-      unknowns: [
-        createJavaScriptSemanticGraphUnknown({
-          ...unknownInput,
-          candidate_node_ids: [`jsrg_node_${"f".repeat(64)}`],
-        }),
+  const validatedUnknownGraph =
+    createJavaScriptSemanticGraph(unknownGraphInput);
+  const evidenceContexts = registryForGraph(validatedUnknownGraph);
+  unknownGraphInput.unknowns = [
+    createJavaScriptSemanticGraphUnknown(
+      {
+        ...unknownInput,
+        candidate_node_ids: [`jsrg_node_${"f".repeat(64)}`],
+        evidence: resolveJavaScriptSemanticEvidence(
+          validatedUnknownGraph,
+          originalUnknown.evidence,
+        ),
+      },
+      evidenceContexts,
+    ),
+  ];
+  unknownGraphInput.evidence_contexts = evidenceContexts.contexts;
+  expect(() => createJavaScriptSemanticGraph(unknownGraphInput)).toThrow(
+    /candidate node is absent/u,
+  );
+});
+
+it("validates evidence context ownership and references", () => {
+  const graph = fixtureGraph();
+  const alteredContext = {
+    ...graph,
+    evidence_contexts: graph.evidence_contexts.map((context, index) =>
+      index === 0
+        ? { ...context, context_id: `jsrg_evidence_${"f".repeat(64)}` }
+        : context,
+    ),
+  };
+  const alteredIssues = javaScriptSemanticGraphSchema.safeParse(alteredContext);
+  expect(alteredIssues.success).toBe(false);
+  if (alteredIssues.success) throw new Error("Expected invalid context digest");
+  expect(alteredIssues.error.issues.map(({ message }) => message)).toContain(
+    "Evidence context identifier is stale",
+  );
+  expect(alteredIssues.error.issues.map(({ message }) => message)).toContain(
+    "Evidence reference names an absent context",
+  );
+
+  const changedPayload = javaScriptSemanticGraphSchema.safeParse({
+    ...graph,
+    evidence_contexts: graph.evidence_contexts.map((context, index) =>
+      index === 0 ? { ...context, authority: "user-assertion" } : context,
+    ),
+  });
+  expect(changedPayload.success).toBe(false);
+  if (changedPayload.success)
+    throw new Error("Expected changed context payload rejection");
+  expect(changedPayload.error.issues.map(({ message }) => message)).toContain(
+    "Evidence context identifier is stale",
+  );
+
+  const withUnknown = fixtureGraph(true);
+  const extraContext = withUnknown.evidence_contexts.find(
+    ({ context_id }) =>
+      !graph.evidence_contexts.some(
+        (existing) => existing.context_id === context_id,
+      ),
+  );
+  if (extraContext === undefined)
+    throw new Error("Expected the unknown fact to own a distinct context");
+  const orphanIssues = javaScriptSemanticGraphSchema.safeParse({
+    ...graph,
+    evidence_contexts: [...graph.evidence_contexts, extraContext].toSorted(
+      (left, right) => left.context_id.localeCompare(right.context_id),
+    ),
+  });
+  expect(orphanIssues.success).toBe(false);
+  if (orphanIssues.success)
+    throw new Error("Expected orphan context rejection");
+  expect(orphanIssues.error.issues.map(({ message }) => message)).toContain(
+    "Evidence context is not referenced by a graph fact",
+  );
+
+  for (const fact of [
+    "nodes",
+    "relations",
+    "unknowns",
+    "fingerprints",
+  ] as const) {
+    const facts = withUnknown[fact];
+    const first = facts[0];
+    if (first === undefined) throw new Error(`Expected a ${fact} fact`);
+    const dangling = javaScriptSemanticGraphSchema.safeParse({
+      ...withUnknown,
+      [fact]: [
+        {
+          ...first,
+          evidence: {
+            ...first.evidence,
+            context_id: `jsrg_evidence_${"e".repeat(64)}`,
+          },
+        },
+        ...facts.slice(1),
       ],
-    }),
-  ).toThrow(/candidate node is absent/u);
+    });
+    expect(dangling.success, fact).toBe(false);
+    if (dangling.success)
+      throw new Error(`Expected dangling ${fact} reference`);
+    expect(
+      dangling.error.issues.map(({ message }) => message),
+      fact,
+    ).toContain("Evidence reference names an absent context");
+  }
+
+  const observedNode = graph.nodes[0];
+  if (observedNode === undefined) throw new Error("Expected observed node");
+  const impossibleEvidence = javaScriptSemanticGraphSchema.safeParse({
+    ...graph,
+    nodes: [
+      {
+        ...observedNode,
+        evidence: {
+          ...observedNode.evidence,
+          location: {
+            available: false,
+            reason: "not-observed",
+            detail: "Location removed from an observed fact.",
+          },
+        },
+      },
+      ...graph.nodes.slice(1),
+    ],
+  });
+  expect(impossibleEvidence.success).toBe(false);
+  if (impossibleEvidence.success)
+    throw new Error("Expected incompatible evidence context and location");
+  expect(
+    impossibleEvidence.error.issues.map(({ message }) => message),
+  ).toContain("Evidence context is incompatible with its fact location");
+});
+
+it("shares provenance contexts while preserving fact-specific locations and unknown IDs", () => {
+  const graph = fixtureGraph(true);
+  const first = graph.unknowns[0];
+  if (first === undefined) throw new Error("Expected an unknown frontier");
+  const evidenceContexts = registryForGraph(graph);
+  const { unknown_id: _unknownId, ...unknown } = first;
+  const second = createJavaScriptSemanticGraphUnknown(
+    {
+      ...unknown,
+      evidence: {
+        ...resolveJavaScriptSemanticEvidence(graph, first.evidence),
+        location: {
+          available: false,
+          reason: "unresolved",
+          detail: "Another source location remains unresolved.",
+        },
+      },
+    },
+    evidenceContexts,
+  );
+  expect(second.evidence.context_id).toBe(first.evidence.context_id);
+  expect(second.evidence.location).not.toEqual(first.evidence.location);
+  expect(second.unknown_id).not.toBe(first.unknown_id);
+  expect(evidenceContexts.contexts).toEqual(graph.evidence_contexts);
 });
 
 const complete = (steps: Iterator): Value => {
@@ -298,7 +499,7 @@ const complete = (steps: Iterator): Value => {
 };
 
 it("captures nested input before yielding and preserves the synchronous graph commitment", () => {
-  const { graph_id: _graphId, ...input } = fixtureGraph(true);
+  const input = fixtureInput(true);
   const node = input.nodes[0];
   if (node === undefined) throw new Error("Expected fixture node");
   const nested = { text: 'Unicode: \u{1f600} \ud800 " \\ ', rows: [1, 2, 3] };
@@ -346,17 +547,16 @@ const invalidGraphCases: {
     message: "Node identifier is stale",
   },
   {
-    label: "relation identity, endpoints and authority",
+    label: "relation endpoints and authority",
     change: (input) => {
       input.relations = input.relations.map((relation) => ({
         ...relation,
         source_node_id: `jsrg_node_${"f".repeat(64)}`,
         target_node_id: `jsrg_node_${"f".repeat(64)}`,
         resolution: "candidate",
-        evidence: evidence(),
       }));
     },
-    message: "Relation identifier is stale",
+    message: "Relation endpoints must name semantic nodes",
   },
   {
     label: "unknown identity and candidates",
@@ -364,7 +564,6 @@ const invalidGraphCases: {
       input.unknowns = input.unknowns.map((unknown) => ({
         ...unknown,
         candidate_node_ids: [`jsrg_node_${"f".repeat(64)}`],
-        evidence: evidence(),
       }));
     },
     message: "Unknown frontier candidate node is absent",
@@ -398,7 +597,7 @@ const invalidGraphCases: {
 it.each(invalidGraphCases)(
   "retains full validation diagnostics for $label in owned steps",
   ({ change, message }) => {
-    const { graph_id: _graphId, ...input } = fixtureGraph(true);
+    const input = fixtureInput(true);
     change(input);
     const issues = (action: () => unknown) => {
       try {
diff --git a/src/domain/javascript/javascriptSemanticGraphSchemas.ts b/src/domain/javascript/javascriptSemanticGraphSchemas.ts
index 64e704198..fb03f1a4d 100644
--- a/src/domain/javascript/javascriptSemanticGraphSchemas.ts
+++ b/src/domain/javascript/javascriptSemanticGraphSchemas.ts
@@ -1,6 +1,10 @@
 import { z } from "zod";
 
-import { applicationGraphEvidenceSchema } from "./javascriptApplicationEvidenceSchemas.js";
+import {
+  applicationGraphEvidenceContextSchema,
+  applicationGraphEvidenceLocationSchema,
+  applicationGraphEvidenceSchema,
+} from "./javascriptApplicationEvidenceSchemas.js";
 import { jsonValueSchema } from "../jsonValue.js";
 import { digestSchema } from "../digests.js";
 import { prefixedDigestSchema } from "../digests.js";
@@ -13,6 +17,21 @@ const semanticRelationIdSchema = z
 const semanticUnknownIdSchema = z
   .string()
   .regex(/^jsrg_unknown_[a-f0-9]{64}$/u);
+const semanticEvidenceContextIdSchema = z
+  .string()
+  .regex(/^jsrg_evidence_[a-f0-9]{64}$/u);
+
+/** One canonical owner for provenance shared by semantic graph facts. */
+export const javaScriptSemanticEvidenceContextSchema =
+  applicationGraphEvidenceContextSchema.extend({
+    context_id: semanticEvidenceContextIdSchema,
+  });
+
+/** Location-specific reference to one exact graph-level evidence context. */
+export const javaScriptSemanticEvidenceReferenceSchema = z.strictObject({
+  context_id: semanticEvidenceContextIdSchema,
+  location: applicationGraphEvidenceLocationSchema,
+});
 
 /** Semantic entity kinds admitted by JavaScript Semantic Relation Graph. */
 export const JAVASCRIPT_SEMANTIC_NODE_KINDS = [
@@ -213,6 +232,7 @@ export const javaScriptSemanticNodeInputSchema = z.strictObject({
 /** One exact, artifact-version semantic entity. */
 export const javaScriptSemanticNodeSchema =
   javaScriptSemanticNodeInputSchema.extend({
+    evidence: javaScriptSemanticEvidenceReferenceSchema,
     node_id: semanticNodeIdSchema,
     identifier_strategy: z.strictObject({
       strategy: z.literal("semantic-content-sha256"),
@@ -233,6 +253,7 @@ export const javaScriptSemanticRelationInputSchema = z.strictObject({
 /** One canonical directed semantic relationship. */
 export const javaScriptSemanticRelationSchema =
   javaScriptSemanticRelationInputSchema.extend({
+    evidence: javaScriptSemanticEvidenceReferenceSchema,
     relation_id: semanticRelationIdSchema,
     identifier_strategy: z.strictObject({
       strategy: z.literal("semantic-content-sha256"),
@@ -269,6 +290,7 @@ export const javaScriptSemanticUnknownInputSchema = z.strictObject({
 /** One canonical unresolved semantic frontier. */
 export const javaScriptSemanticUnknownSchema =
   javaScriptSemanticUnknownInputSchema.extend({
+    evidence: javaScriptSemanticEvidenceReferenceSchema,
     unknown_id: semanticUnknownIdSchema,
   });
 
@@ -304,6 +326,7 @@ export const javaScriptSemanticFingerprintInputSchema = z.strictObject({
 /** One canonical function fingerprint record. */
 export const javaScriptSemanticFingerprintSchema =
   javaScriptSemanticFingerprintInputSchema.extend({
+    evidence: javaScriptSemanticEvidenceReferenceSchema,
     fingerprint_id: prefixedDigestSchema("jsrg_fingerprint"),
     fingerprint_sha256: digestSchema,
   });
@@ -337,6 +360,7 @@ export const javaScriptSemanticGraphInputSchema = z.strictObject({
   root_artifact_sha256: digestSchema,
   application_graph_id: prefixedDigestSchema("jag"),
   root_node_ids: z.array(semanticNodeIdSchema).min(1),
+  evidence_contexts: z.array(javaScriptSemanticEvidenceContextSchema),
   nodes: z.array(javaScriptSemanticNodeSchema).min(1),
   relations: z.array(javaScriptSemanticRelationSchema),
   fingerprints: z.array(javaScriptSemanticFingerprintSchema),
@@ -355,6 +379,14 @@ export const javaScriptSemanticGraphRecordSchema =
 export type JavaScriptSemanticGraphNode = z.infer<
   typeof javaScriptSemanticNodeSchema
 >;
+/** Compact provenance on one graph fact. */
+export type JavaScriptSemanticEvidenceReference = z.infer<
+  typeof javaScriptSemanticEvidenceReferenceSchema
+>;
+/** Content-addressed graph-level provenance context. */
+export type JavaScriptSemanticEvidenceContext = z.infer<
+  typeof javaScriptSemanticEvidenceContextSchema
+>;
 /** Canonical semantic relation. */
 export type JavaScriptSemanticGraphRelation = z.infer<
   typeof javaScriptSemanticRelationSchema
@@ -363,6 +395,10 @@ export type JavaScriptSemanticGraphRelation = z.infer<
 export type JavaScriptSemanticGraphUnknown = z.infer<
   typeof javaScriptSemanticUnknownSchema
 >;
+/** Canonical function fingerprint with a compact evidence reference. */
+export type JavaScriptSemanticFingerprint = z.infer<
+  typeof javaScriptSemanticFingerprintSchema
+>;
 /** Canonical graph content before graph ID derivation. */
 export type JavaScriptSemanticGraphInput = z.infer<
   typeof javaScriptSemanticGraphInputSchema
diff --git a/src/domain/javascript/javascriptSemanticGraphTraversal.test.ts b/src/domain/javascript/javascriptSemanticGraphTraversal.test.ts
index 532c1fe28..e42af295f 100644
--- a/src/domain/javascript/javascriptSemanticGraphTraversal.test.ts
+++ b/src/domain/javascript/javascriptSemanticGraphTraversal.test.ts
@@ -5,6 +5,7 @@ import {
   JAVASCRIPT_SEMANTIC_NODE_KINDS,
   JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
   JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
+  type JavaScriptSemanticGraphInput,
 } from "./javascriptSemanticGraphSchemas.js";
 import {
   createJavaScriptSemanticFingerprint,
@@ -12,6 +13,8 @@ import {
   createJavaScriptSemanticGraphNode,
   createJavaScriptSemanticGraphRelation,
   createJavaScriptSemanticGraphUnknown,
+  JavaScriptSemanticEvidenceContextRegistry,
+  resolveJavaScriptSemanticEvidence,
   type JavaScriptSemanticGraph,
 } from "./javascriptSemanticGraph.js";
 import type {
@@ -96,71 +99,92 @@ const unknownEvidence = (): ApplicationGraphEvidence => ({
 const node = (
   kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
   role: string,
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
   properties: Record = {},
   functionNodeId: string | null = null,
 ): JavaScriptSemanticGraphNode =>
-  createJavaScriptSemanticGraphNode({
-    kind,
-    identity: {
-      artifact_sha256: SHA,
-      module_path: "bundle.js",
-      source_range: {
-        start: { line: 1, column: role.length },
-        end: { line: 1, column: role.length + 1 },
+  createJavaScriptSemanticGraphNode(
+    {
+      kind,
+      identity: {
+        artifact_sha256: SHA,
+        module_path: "bundle.js",
+        source_range: {
+          start: { line: 1, column: role.length },
+          end: { line: 1, column: role.length + 1 },
+        },
+        role_key: role,
       },
-      role_key: role,
+      function_node_id: functionNodeId,
+      application_node_ids: [],
+      label: role,
+      properties,
+      evidence: evidence(),
     },
-    function_node_id: functionNodeId,
-    application_node_ids: [],
-    label: role,
-    properties,
-    evidence: evidence(),
-  });
+    evidenceContexts,
+  );
 
 const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
-  const module = node("module", "module");
-  const literal = node("literal", "literal", { value: "TOKEN" });
-  const binding = node("binding", "binding");
-  const callable = node("function", "function");
-  const request = node("request", "request", {
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const module = node("module", "module", evidenceContexts);
+  const literal = node("literal", "literal", evidenceContexts, {
+    value: "TOKEN",
+  });
+  const binding = node("binding", "binding", evidenceContexts);
+  const callable = node("function", "function", evidenceContexts);
+  const request = node("request", "request", evidenceContexts, {
     endpoint: "https://example.invalid/v1",
   });
   const relations = [
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: literal.node_id,
-      target_node_id: binding.node_id,
-      relation: "defines",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: binding.node_id,
-      target_node_id: callable.node_id,
-      relation: "captures",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: callable.node_id,
-      target_node_id: request.node_id,
-      relation: "constructs-request",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: literal.node_id,
+        target_node_id: binding.node_id,
+        relation: "defines",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: binding.node_id,
+        target_node_id: callable.node_id,
+        relation: "captures",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: callable.node_id,
+        target_node_id: request.node_id,
+        relation: "constructs-request",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
   ];
-  const dynamic = createJavaScriptSemanticGraphUnknown({
-    node_id: callable.node_id,
-    family: "call-flow",
-    relation_kinds: ["calls"],
-    reason: "dynamic-call",
-    detail: "Computed callee is unresolved.",
-    candidate_node_ids: [],
-    evidence: unknownEvidence(),
-  });
-  const unknowns = withUnknown ? [dynamic] : [];
+  const dynamic = withUnknown
+    ? createJavaScriptSemanticGraphUnknown(
+        {
+          node_id: callable.node_id,
+          family: "call-flow",
+          relation_kinds: ["calls"],
+          reason: "dynamic-call",
+          detail: "Computed callee is unresolved.",
+          candidate_node_ids: [],
+          evidence: unknownEvidence(),
+        },
+        evidenceContexts,
+      )
+    : null;
+  const unknowns = dynamic === null ? [] : [dynamic];
   const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
     (family) => ({
       family,
@@ -177,29 +201,33 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
       ).length,
       omitted_relations: withUnknown && family === "call-flow" ? null : 0,
       unknown_ids:
-        withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
+        dynamic !== null && family === "call-flow" ? [dynamic.unknown_id] : [],
     }),
   );
-  const fingerprint = createJavaScriptSemanticFingerprint({
-    function_node_id: callable.node_id,
-    algorithm: "rea.javascript-semantic-function",
-    status: "complete",
-    components: {
-      parameter_arity: 0,
-      normalized_ast_sha256: "1".repeat(64),
-      control_flow_sha256: "2".repeat(64),
-      relation_shape_sha256: "3".repeat(64),
-      literal_set_sha256: "4".repeat(64),
-      effects: ["network"],
+  const fingerprint = createJavaScriptSemanticFingerprint(
+    {
+      function_node_id: callable.node_id,
+      algorithm: "rea.javascript-semantic-function",
+      status: "complete",
+      components: {
+        parameter_arity: 0,
+        normalized_ast_sha256: "1".repeat(64),
+        control_flow_sha256: "2".repeat(64),
+        relation_shape_sha256: "3".repeat(64),
+        literal_set_sha256: "4".repeat(64),
+        effects: ["network"],
+      },
+      limitations: [],
+      evidence: evidence("inferred"),
     },
-    limitations: [],
-    evidence: evidence("inferred"),
-  });
+    evidenceContexts,
+  );
   return createJavaScriptSemanticGraph({
     schema: "JavaScriptSemanticRelationGraph",
     root_artifact_sha256: SHA,
     application_graph_id: JAG_ID,
     root_node_ids: [module.node_id],
+    evidence_contexts: evidenceContexts.contexts,
     nodes: [request, callable, binding, literal, module],
     relations,
     fingerprints: [fingerprint],
@@ -218,22 +246,27 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
 
 const graphWithCandidateEdge = (): JavaScriptSemanticGraph => {
   const graph = fixtureGraph();
+  const input = constructionInput(graph);
+  const evidenceContexts = registryForGraph(graph);
   const literal = graph.nodes.find(({ kind }) => kind === "literal");
   const request = graph.nodes.find(({ kind }) => kind === "request");
   if (literal === undefined || request === undefined)
     throw new TypeError("Semantic fixture nodes are missing");
-  const candidate = createJavaScriptSemanticGraphRelation({
-    source_node_id: literal.node_id,
-    target_node_id: request.node_id,
-    relation: "supplies-request-field",
-    resolution: "candidate",
-    properties: { field: "authorization" },
-    evidence: evidence("inferred"),
-  });
-  const { graph_id: _graphId, ...input } = graph;
+  const candidate = createJavaScriptSemanticGraphRelation(
+    {
+      source_node_id: literal.node_id,
+      target_node_id: request.node_id,
+      relation: "supplies-request-field",
+      resolution: "candidate",
+      properties: { field: "authorization" },
+      evidence: evidence("inferred"),
+    },
+    evidenceContexts,
+  );
   return createJavaScriptSemanticGraph({
     ...input,
-    relations: [...graph.relations, candidate],
+    evidence_contexts: evidenceContexts.contexts,
+    relations: [...input.relations, candidate],
     coverage: {
       ...graph.coverage,
       families: graph.coverage.families.map((family) =>
@@ -248,6 +281,27 @@ const graphWithCandidateEdge = (): JavaScriptSemanticGraph => {
   });
 };
 
+const constructionInput = (
+  graph: JavaScriptSemanticGraph,
+): JavaScriptSemanticGraphInput => {
+  const { graph_id: _graphId, ...input } = graph;
+  return input;
+};
+
+const registryForGraph = (
+  graph: JavaScriptSemanticGraph,
+): JavaScriptSemanticEvidenceContextRegistry => {
+  const registry = new JavaScriptSemanticEvidenceContextRegistry();
+  for (const { evidence: reference } of [
+    ...graph.nodes,
+    ...graph.relations,
+    ...graph.unknowns,
+    ...graph.fingerprints,
+  ])
+    registry.intern(resolveJavaScriptSemanticEvidence(graph, reference));
+  return registry;
+};
+
 it("returns every relevant unknown inline", () => {
   const graph = fixtureGraph(true);
   const callable = graph.nodes.find(({ kind }) => kind === "function");
@@ -279,28 +333,55 @@ it("returns the complete deterministic forward influence result inline", () => {
   expect(first.relations).toHaveLength(3);
 });
 
+it("returns only the referenced evidence contexts with resolvable trace facts", () => {
+  const graph = fixtureGraph();
+  const result = queryJavaScriptSemanticGraph(graph, {
+    seed: { kind: "literal", value: "TOKEN" },
+    direction: "forward-influence",
+  });
+  const expectedContextIds = [
+    ...new Set([
+      ...result.nodes.map(({ evidence }) => evidence.context_id),
+      ...result.relations.map(({ evidence }) => evidence.context_id),
+      ...result.unknowns.map(({ evidence }) => evidence.context_id),
+    ]),
+  ].sort();
+  expect(result.evidence_contexts.map(({ context_id }) => context_id)).toEqual(
+    expectedContextIds,
+  );
+  for (const node of result.nodes)
+    expect(resolveJavaScriptSemanticEvidence(result, node.evidence)).toEqual(
+      resolveJavaScriptSemanticEvidence(graph, node.evidence),
+    );
+});
+
 it("traverses paths beyond the former fixed depth ceiling", () => {
   const original = fixtureGraph();
+  const input = constructionInput(original);
+  const evidenceContexts = registryForGraph(original);
   const request = original.nodes.find(({ kind }) => kind === "request");
   if (request === undefined) throw new TypeError("Missing request node");
   const chain = Array.from({ length: 70 }, (_, index) =>
-    node("binding", `long-chain-${index}`),
+    node("binding", `long-chain-${index}`, evidenceContexts),
   );
   const chainRelations = chain.map((target, index) =>
-    createJavaScriptSemanticGraphRelation({
-      source_node_id: chain[index - 1]?.node_id ?? request.node_id,
-      target_node_id: target.node_id,
-      relation: "reads",
-      resolution: "resolved",
-      properties: {},
-      evidence: evidence("inferred"),
-    }),
+    createJavaScriptSemanticGraphRelation(
+      {
+        source_node_id: chain[index - 1]?.node_id ?? request.node_id,
+        target_node_id: target.node_id,
+        relation: "reads",
+        resolution: "resolved",
+        properties: {},
+        evidence: evidence("inferred"),
+      },
+      evidenceContexts,
+    ),
   );
-  const { graph_id: _graphId, ...input } = original;
   const graph = createJavaScriptSemanticGraph({
     ...input,
-    nodes: [...original.nodes, ...chain],
-    relations: [...original.relations, ...chainRelations],
+    evidence_contexts: evidenceContexts.contexts,
+    nodes: [...input.nodes, ...chain],
+    relations: [...input.relations, ...chainRelations],
     coverage: {
       ...original.coverage,
       families: original.coverage.families.map((family) =>
@@ -329,7 +410,12 @@ it("accepts deeply nested semantic properties", () => {
   for (let index = 0; index < 12; index += 1)
     nested = { [`level-${String(index)}`]: nested };
 
-  const result = node("binding", "deep-properties", { nested });
+  const result = node(
+    "binding",
+    "deep-properties",
+    new JavaScriptSemanticEvidenceContextRegistry(),
+    { nested },
+  );
 
   expect(result.properties).toEqual({ nested });
 });
@@ -369,41 +455,50 @@ it("excludes candidate edges unless the caller explicitly opts in", () => {
 });
 
 it("retains every structural application node linked to one semantic node", () => {
-  const original = node("module", "module");
-  const linked = createJavaScriptSemanticGraphNode({
-    kind: original.kind,
-    identity: original.identity,
-    function_node_id: original.function_node_id,
-    application_node_ids: Array.from(
-      { length: 65 },
-      (_, index) => `jag_node_${index.toString(16).padStart(64, "0")}`,
-    ),
-    label: original.label,
-    properties: original.properties,
-    evidence: original.evidence,
-  });
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const original = node("module", "module", evidenceContexts);
+  const linked = createJavaScriptSemanticGraphNode(
+    {
+      kind: original.kind,
+      identity: original.identity,
+      function_node_id: original.function_node_id,
+      application_node_ids: Array.from(
+        { length: 65 },
+        (_, index) => `jag_node_${index.toString(16).padStart(64, "0")}`,
+      ),
+      label: original.label,
+      properties: original.properties,
+      evidence: evidenceContexts.resolve(original.evidence),
+    },
+    evidenceContexts,
+  );
   expect(linked.application_node_ids).toHaveLength(65);
 });
 
 it("retains all explicit unresolved candidate node identifiers", () => {
-  const unknown = createJavaScriptSemanticGraphUnknown({
-    node_id: null,
-    family: "call-flow",
-    relation_kinds: ["calls"],
-    reason: "ambiguous-target",
-    detail: "All candidate targets are retained.",
-    candidate_node_ids: Array.from(
-      { length: 1_001 },
-      (_, index) => `jsrg_node_${index.toString(16).padStart(64, "0")}`,
-    ),
-    evidence: unknownEvidence(),
-  });
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const unknown = createJavaScriptSemanticGraphUnknown(
+    {
+      node_id: null,
+      family: "call-flow",
+      relation_kinds: ["calls"],
+      reason: "ambiguous-target",
+      detail: "All candidate targets are retained.",
+      candidate_node_ids: Array.from(
+        { length: 1_001 },
+        (_, index) => `jsrg_node_${index.toString(16).padStart(64, "0")}`,
+      ),
+      evidence: unknownEvidence(),
+    },
+    evidenceContexts,
+  );
   expect(unknown.candidate_node_ids).toHaveLength(1_001);
 });
 
 const directionalGraph = (
   nodes: readonly JavaScriptSemanticGraphNode[],
   relations: readonly JavaScriptSemanticGraphRelation[],
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
   partial = false,
 ): JavaScriptSemanticGraph =>
   createJavaScriptSemanticGraph({
@@ -411,6 +506,7 @@ const directionalGraph = (
     root_artifact_sha256: SHA,
     application_graph_id: JAG_ID,
     root_node_ids: nodes.slice(0, 1).map(({ node_id }) => node_id),
+    evidence_contexts: evidenceContexts.contexts,
     nodes: [...nodes],
     relations: [...relations],
     fingerprints: [],
@@ -439,16 +535,20 @@ const relationBetween = (
   source: JavaScriptSemanticGraphNode,
   target: JavaScriptSemanticGraphNode,
   relation: JavaScriptSemanticGraphRelation["relation"],
+  evidenceContexts: JavaScriptSemanticEvidenceContextRegistry,
   resolution: JavaScriptSemanticGraphRelation["resolution"] = "resolved",
 ) =>
-  createJavaScriptSemanticGraphRelation({
-    source_node_id: source.node_id,
-    target_node_id: target.node_id,
-    relation,
-    resolution,
-    properties: {},
-    evidence: evidence("inferred"),
-  });
+  createJavaScriptSemanticGraphRelation(
+    {
+      source_node_id: source.node_id,
+      target_node_id: target.node_id,
+      relation,
+      resolution,
+      properties: {},
+      evidence: evidence("inferred"),
+    },
+    evidenceContexts,
+  );
 
 it.each([
   {
@@ -489,25 +589,28 @@ it.each([
 ] as const)(
   "limits $direction ambiguity to traversable $relation candidates (incoming=$incoming)",
   ({ direction, relation, incoming, relevant }) => {
-    const seed = node("function", "directional-seed");
-    const reached = node("function", "directional-reached");
-    const other = node("function", "directional-other");
+    const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+    const seed = node("function", "directional-seed", evidenceContexts);
+    const reached = node("function", "directional-reached", evidenceContexts);
+    const other = node("function", "directional-other", evidenceContexts);
     const reverse =
       direction === "callers" || direction === "backward-provenance";
     const resolved = relationBetween(
       reverse ? reached : seed,
       reverse ? seed : reached,
       direction === "ownership" ? "owns" : "calls",
+      evidenceContexts,
     );
     const candidate = relationBetween(
       incoming ? other : reached,
       incoming ? reached : other,
       relation,
+      evidenceContexts,
       "candidate",
     );
     const nodes = [seed, reached, other];
     const control = queryJavaScriptSemanticGraph(
-      directionalGraph(nodes, [resolved]),
+      directionalGraph(nodes, [resolved], evidenceContexts),
       {
         seed: { kind: "semantic-node", node_id: seed.node_id },
         direction,
@@ -519,7 +622,7 @@ it.each([
     });
     for (const include of [false, true]) {
       const result = queryJavaScriptSemanticGraph(
-        directionalGraph(nodes, [resolved, candidate]),
+        directionalGraph(nodes, [resolved, candidate], evidenceContexts),
         {
           seed: { kind: "semantic-node", node_id: seed.node_id },
           direction,
@@ -535,19 +638,33 @@ it.each([
         expect(result.relations).toEqual(control.relations);
       } else {
         expect(result.nodes).toHaveLength(3);
-        expect(result.relations).toContainEqual(candidate);
+        expect(result.relations).toContainEqual(
+          expect.objectContaining({
+            source_node_id: candidate.source_node_id,
+            target_node_id: candidate.target_node_id,
+            relation: candidate.relation,
+            resolution: candidate.resolution,
+          }),
+        );
       }
     }
   },
 );
 
 it("excludes explicitly filtered candidates without hiding partial graph coverage", () => {
-  const seed = node("function", "filtered-seed");
-  const other = node("function", "filtered-other");
-  const candidate = relationBetween(seed, other, "reads", "candidate");
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
+  const seed = node("function", "filtered-seed", evidenceContexts);
+  const other = node("function", "filtered-other", evidenceContexts);
+  const candidate = relationBetween(
+    seed,
+    other,
+    "reads",
+    evidenceContexts,
+    "candidate",
+  );
   for (const partial of [false, true]) {
     const result = queryJavaScriptSemanticGraph(
-      directionalGraph([seed, other], [candidate], partial),
+      directionalGraph([seed, other], [candidate], evidenceContexts, partial),
       {
         seed: { kind: "semantic-node", node_id: seed.node_id },
         direction: "forward-influence",
@@ -563,8 +680,9 @@ it("excludes explicitly filtered candidates without hiding partial graph coverag
 });
 
 it("keeps candidate uncertainty at the end of a long reachable path", () => {
+  const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
   const chain = Array.from({ length: 72 }, (_, index) =>
-    node("binding", `candidate-chain-${index}`),
+    node("binding", `candidate-chain-${index}`, evidenceContexts),
   );
   const relations = chain.slice(1).map((target, index) => {
     const source = chain[index];
@@ -573,6 +691,7 @@ it("keeps candidate uncertainty at the end of a long reachable path", () => {
       source,
       target,
       "reads",
+      evidenceContexts,
       index === 70 ? "candidate" : "resolved",
     );
   });
@@ -580,7 +699,7 @@ it("keeps candidate uncertainty at the end of a long reachable path", () => {
   if (seed === undefined) throw new TypeError("Missing chain seed");
   for (const include of [false, true]) {
     const result = queryJavaScriptSemanticGraph(
-      directionalGraph(chain, relations),
+      directionalGraph(chain, relations, evidenceContexts),
       {
         seed: { kind: "semantic-node", node_id: seed.node_id },
         direction: "forward-influence",
diff --git a/src/domain/javascript/javascriptSemanticQuery.ts b/src/domain/javascript/javascriptSemanticQuery.ts
index e793ccede..6439d8954 100644
--- a/src/domain/javascript/javascriptSemanticQuery.ts
+++ b/src/domain/javascript/javascriptSemanticQuery.ts
@@ -68,6 +68,11 @@ export const queryJavaScriptSemanticGraph = (
     result.retainedRelations,
     input,
   );
+  const retainedContextIds = new Set([
+    ...result.retainedNodes.map(({ evidence }) => evidence.context_id),
+    ...result.retainedRelations.map(({ evidence }) => evidence.context_id),
+    ...relevantUnknowns.map(({ evidence }) => evidence.context_id),
+  ]);
   const assessment = assessJavaScriptSemanticQuery({
     graph,
     totalSeeds: seeds.length,
@@ -83,6 +88,9 @@ export const queryJavaScriptSemanticGraph = (
     direction: input.direction,
     status: assessment.status,
     seed_node_ids: retainedSeeds,
+    evidence_contexts: graph.evidence_contexts.filter(({ context_id }) =>
+      retainedContextIds.has(context_id),
+    ),
     nodes: result.retainedNodes,
     relations: result.retainedRelations,
     unknowns: relevantUnknowns,
diff --git a/src/domain/javascript/javascriptSemanticQuerySchemas.ts b/src/domain/javascript/javascriptSemanticQuerySchemas.ts
index 0cd94e280..d9c93446a 100644
--- a/src/domain/javascript/javascriptSemanticQuerySchemas.ts
+++ b/src/domain/javascript/javascriptSemanticQuerySchemas.ts
@@ -5,6 +5,7 @@ import {
   JAVASCRIPT_SEMANTIC_RELATIONS,
   javaScriptSemanticNodeSchema,
   javaScriptSemanticRelationSchema,
+  javaScriptSemanticEvidenceContextSchema,
   javaScriptSemanticUnknownSchema,
 } from "./javascriptSemanticGraphSchemas.js";
 import { jsonValueSchema } from "../jsonValue.js";
@@ -93,6 +94,7 @@ export const javaScriptSemanticQueryResultSchema = z.strictObject({
   direction: javaScriptSemanticQueryInputSchema.shape.direction,
   status: z.enum(["found", "no-match", "ambiguous", "partial", "unsupported"]),
   seed_node_ids: z.array(semanticNodeIdSchema),
+  evidence_contexts: z.array(javaScriptSemanticEvidenceContextSchema),
   nodes: z.array(javaScriptSemanticNodeSchema),
   relations: z.array(javaScriptSemanticRelationSchema),
   unknowns: z.array(javaScriptSemanticUnknownSchema),
diff --git a/tests/boundary/mcp/applicationExportShapeMcp.test.ts b/tests/boundary/mcp/applicationExportShapeMcp.test.ts
index a35b92abc..8ba6bc0bf 100644
--- a/tests/boundary/mcp/applicationExportShapeMcp.test.ts
+++ b/tests/boundary/mcp/applicationExportShapeMcp.test.ts
@@ -88,7 +88,10 @@ it("traces example semantic modules with their parsed artifact digests", async (
     const module = analysis.semantic_graph.nodes.find(
       ({ kind }) => kind === "module",
     );
-    if (module === undefined || !module.evidence.artifact.available)
+    const evidenceContext = analysis.semantic_graph.evidence_contexts.find(
+      ({ context_id }) => context_id === module?.evidence.context_id,
+    );
+    if (module === undefined || !evidenceContext?.artifact.available)
       throw new Error("Example must retain an artifact-backed semantic module");
     const response = await client.callTool({
       name: "trace_javascript_semantics",
@@ -103,11 +106,19 @@ it("traces example semantic modules with their parsed artifact digests", async (
     expect(response.isError).not.toBe(true);
     expect(response.structuredContent).toMatchObject({
       normalized_result: {
+        evidence_contexts: expect.arrayContaining([
+          expect.objectContaining({
+            context_id: module.evidence.context_id,
+            artifact: expect.objectContaining({
+              sha256: evidenceContext.artifact.sha256,
+            }),
+          }),
+        ]),
         nodes: expect.arrayContaining([
           expect.objectContaining({
             node_id: module.node_id,
             identity: expect.objectContaining({
-              artifact_sha256: module.evidence.artifact.sha256,
+              artifact_sha256: evidenceContext.artifact.sha256,
             }),
           }),
         ]),

From a4ba8aecd507637b6261026afc17f79516840d50 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 03:11:08 +0800
Subject: [PATCH 069/189] fix(contracts)!: require observed provider output
 metadata

Reject omitted segment bounds, procedure classification and body facts, unresolved-call observations, dossier facets, and Ghidra parameter flow metadata. Providers emit explicit nulls for unsupported facets. Verify those unknowns in the real Hopper workflow.

BREAKING CHANGE: Provider analysis outputs must explicitly supply metadata previously repaired with defaults; unsupported nullable facets must be reported as null.
---
 bridge/hopper_bridge.py                       |  2 +
 scripts/lib/real-hopper-navigation.mjs        | 18 ++++++
 scripts/lib/real-hopper-semantic.mjs          | 28 ++++++++-
 scripts/verify/managed/config.mjs             |  6 ++
 .../native/NativeApiInspection.test.ts        |  6 +-
 .../native/NativeCallRoutes.test.ts           | 26 ++++++++
 src/application/native/NativeCallRoutes.ts    |  8 +--
 .../native/NativeValueTrace.test.ts           |  5 ++
 src/contracts/functionComparisonExample.ts    |  8 +++
 src/contracts/toolOutputSchemaGroups.ts       |  4 +-
 src/contracts/toolOutputSchemaPrimitives.ts   |  7 +--
 src/domain/callPath.test.ts                   | 15 +++++
 src/domain/functionComparison.test.ts         | 51 +++++++++-------
 src/domain/ghidraValues.fixture.ts            |  3 +
 src/domain/hopperValues.test.ts               | 30 ++++++++--
 src/domain/hopperValues.ts                    | 28 ++++-----
 src/domain/native/nativeValueFlow.ts          | 36 +++++------
 ...uctionVerification.functionSources.test.ts |  9 +++
 src/ghidra/GhidraFunctionValues.test.ts       | 49 +++++++++++++++
 src/ida/IdaOperationRunner.ts                 |  2 +
 src/ida/IdaSessionClient.test.ts              | 11 ++++
 ....01-lists-the-complete-target-open.test.ts | 59 ++++++++++++-------
 ...4-uses-complete-inventories-inline.test.ts | 58 +++++++++++++++++-
 ...ts-incomplete-function-dossiers-at.test.ts | 32 ++++++++++
 .../mcp/investigationAnalysisMcp.test.ts      | 10 +++-
 .../mcp/workflowSnapshotReplayMcp.test.ts     | 11 +++-
 .../hopper/hopperBridgeFacade.test.ts         | 15 +++++
 .../directAnalysisSnapshotReplay.test.ts      | 16 ++++-
 tests/fixtures/hopperBridgeFacadeProbe.py     | 24 ++++++++
 29 files changed, 465 insertions(+), 112 deletions(-)

diff --git a/bridge/hopper_bridge.py b/bridge/hopper_bridge.py
index ab7b84ee0..440085637 100644
--- a/bridge/hopper_bridge.py
+++ b/bridge/hopper_bridge.py
@@ -716,6 +716,8 @@ def _analyze_function(document, params):
         "referenced_strings": referenced_strings,
         "referenced_names": referenced_names,
         "basic_blocks": blocks,
+        "native_api": None,
+        "native_value_flow": None,
         "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/scripts/lib/real-hopper-navigation.mjs b/scripts/lib/real-hopper-navigation.mjs
index 3ee47a7a5..c4096d869 100644
--- a/scripts/lib/real-hopper-navigation.mjs
+++ b/scripts/lib/real-hopper-navigation.mjs
@@ -58,6 +58,12 @@ async function verifyNavigation(
     procedure: address,
   });
   const info = await call("procedure_info", { procedure: address });
+  assert.equal(info.classification, null);
+  assert.equal(info.body.available, false);
+  assert.match(
+    info.body.reason,
+    /public Python API does not expose complete function body ranges/u,
+  );
   assert.ok(info.locals.length > 0, "fixture omitted real stack locals");
   for (const local of info.locals) {
     assert.equal(typeof local.name, "string");
@@ -68,6 +74,18 @@ async function verifyNavigation(
   }
   const dossier = await call("analyze_function", { procedure: address });
   assert.deepEqual(dossier.procedure.locals, info.locals);
+  assert.equal(dossier.procedure.classification, null);
+  assert.equal(dossier.procedure.body.available, false);
+  assert.match(
+    dossier.procedure.body.reason,
+    /public Python API does not expose complete function body ranges/u,
+  );
+  assert.equal(dossier.native_api, null);
+  assert.equal(dossier.native_value_flow, null);
+  assert.ok(
+    Array.isArray(dossier.limitations) && dossier.limitations.length > 0,
+    "function dossier omitted Hopper's unsupported-facet limitations",
+  );
   const coordinates = instructions.instructions.map(
     (line) => /^0x[0-9a-f]+/u.exec(line)?.[0],
   );
diff --git a/scripts/lib/real-hopper-semantic.mjs b/scripts/lib/real-hopper-semantic.mjs
index 412900d7c..000b806d0 100644
--- a/scripts/lib/real-hopper-semantic.mjs
+++ b/scripts/lib/real-hopper-semantic.mjs
@@ -11,15 +11,28 @@ export const requireTruthfulMemoryRegions = (segments) => {
     ...(Array.isArray(segment.sections) ? segment.sections : []),
   ]);
   for (const region of regions) {
+    if (
+      typeof region?.name !== "string" ||
+      region.name.length === 0 ||
+      typeof region.start !== "string" ||
+      typeof region.end !== "string"
+    ) {
+      throw new Error(
+        "list_segments omitted observed region identity or bounds",
+      );
+    }
     for (const permission of ["readable", "writable", "executable"]) {
-      if (![true, false, null].includes(region?.[permission])) {
-        throw new Error(`list_segments omitted tri-state ${permission}`);
+      if (region[permission] !== null) {
+        throw new Error(
+          `list_segments invented or omitted unknown ${permission}`,
+        );
       }
     }
     if (
       region.provenance !== "hopper-public-python-api" ||
       region.permissions?.available !== false ||
-      typeof region.permissions.reason !== "string"
+      typeof region.permissions.reason !== "string" ||
+      region.permissions.reason.length === 0
     ) {
       throw new Error("list_segments omitted permission provenance");
     }
@@ -141,6 +154,15 @@ export async function verifyRealHopperFixture({
     "procedure_references",
   );
   assert.deepEqual(entryDossier.unresolved_calls, observed.unresolved_calls);
+  assert.equal(
+    observed.reference_kinds_available,
+    false,
+    "Hopper's partial CallReference observations do not expose detailed reference kinds",
+  );
+  assert.ok(
+    Array.isArray(observed.unresolved_calls),
+    "procedure_references omitted its observed unresolved CallReference results",
+  );
   for (const call of calls) {
     assert.equal(call.call.provider_type, 2);
     assert.equal(
diff --git a/scripts/verify/managed/config.mjs b/scripts/verify/managed/config.mjs
index 352f0443d..f22b15d18 100644
--- a/scripts/verify/managed/config.mjs
+++ b/scripts/verify/managed/config.mjs
@@ -62,6 +62,10 @@ export function functionDossier(name) {
         thunk_target: null,
         provenance: "synthetic-provider",
       },
+      body: {
+        available: false,
+        reason: "Synthetic provider does not supply function body ranges.",
+      },
       signature: null,
       locals: [],
     },
@@ -75,6 +79,8 @@ export function functionDossier(name) {
     referenced_strings: [],
     referenced_names: [],
     basic_blocks: [],
+    native_api: null,
+    native_value_flow: null,
     limitations: [],
   };
 }
diff --git a/src/application/native/NativeApiInspection.test.ts b/src/application/native/NativeApiInspection.test.ts
index db0c61a19..d3bd88b7b 100644
--- a/src/application/native/NativeApiInspection.test.ts
+++ b/src/application/native/NativeApiInspection.test.ts
@@ -100,11 +100,7 @@ describe("native API inspection", () => {
     const value = ghidraFunctionDossier();
     if (typeof value !== "object" || value === null || Array.isArray(value))
       throw new TypeError("Ghidra dossier fixture is invalid");
-    const dossier = functionDossierSchema.parse(
-      Object.fromEntries(
-        Object.entries(value).filter(([key]) => key !== "native_api"),
-      ),
-    );
+    const dossier = functionDossierSchema.parse({ ...value, native_api: null });
 
     expect(projectNativeApiInspection(dossier)).toMatchObject({
       boundary: { available: false },
diff --git a/src/application/native/NativeCallRoutes.test.ts b/src/application/native/NativeCallRoutes.test.ts
index baac1d16a..e54a55dc5 100644
--- a/src/application/native/NativeCallRoutes.test.ts
+++ b/src/application/native/NativeCallRoutes.test.ts
@@ -101,4 +101,30 @@ describe("typed native call routes", () => {
       error: { _tag: "AnalysisOutputError" },
     });
   });
+  it("rejects omitted unresolved-call observations instead of claiming none", async () => {
+    let calls = 0;
+    const result = await readNativeCallRoutes(
+      {
+        execute: async () => {
+          calls++;
+          return ok(
+            createAnalysisExecution(
+              {
+                reference_kinds_available: false,
+                references: [],
+              },
+              provider,
+            ),
+          );
+        },
+      },
+      "0x1000",
+    );
+
+    expect(result).toMatchObject({
+      ok: false,
+      error: { _tag: "AnalysisOutputError" },
+    });
+    expect(calls).toBe(1);
+  });
 });
diff --git a/src/application/native/NativeCallRoutes.ts b/src/application/native/NativeCallRoutes.ts
index adb286195..bb819d742 100644
--- a/src/application/native/NativeCallRoutes.ts
+++ b/src/application/native/NativeCallRoutes.ts
@@ -8,7 +8,7 @@ import { err, ok } from "../../domain/result.js";
 import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
 
 const referencesSchema = z.object({
-  reference_kinds_available: z.boolean().optional(),
+  reference_kinds_available: z.boolean(),
   references: z.array(
     z.object({
       source_address: z.string(),
@@ -17,9 +17,9 @@ const referencesSchema = z.object({
       kind: referenceKindSchema,
     }),
   ),
-  unresolved_calls: z
-    .array(z.object({ address: z.string(), reason: z.string() }))
-    .default([]),
+  unresolved_calls: z.array(
+    z.object({ address: z.string(), reason: z.string() }),
+  ),
 });
 /** Prefer typed static call references, preserving computed targets and targetless sites. */
 export const readNativeCallRoutes = async (
diff --git a/src/application/native/NativeValueTrace.test.ts b/src/application/native/NativeValueTrace.test.ts
index 7f9be52d9..0d2b19c77 100644
--- a/src/application/native/NativeValueTrace.test.ts
+++ b/src/application/native/NativeValueTrace.test.ts
@@ -67,6 +67,11 @@ const analysis: AnalysisOperationPort = {
             address: callee ? "0x2000" : "0x1000",
             name: callee ? "callee" : "caller",
             classification: null,
+            body: {
+              available: false,
+              reason:
+                "The provider did not report complete function body ranges.",
+            },
             signature: null,
             locals: [],
           },
diff --git a/src/contracts/functionComparisonExample.ts b/src/contracts/functionComparisonExample.ts
index 5229dc6cd..2ba8581d9 100644
--- a/src/contracts/functionComparisonExample.ts
+++ b/src/contracts/functionComparisonExample.ts
@@ -7,6 +7,11 @@ const dossier = (text: string) =>
     procedure: {
       address: "0x1000",
       name: "main",
+      classification: null,
+      body: {
+        available: false,
+        reason: "The fixture omits function-body extent observations.",
+      },
       signature: "int main(void)",
       locals: [],
     },
@@ -20,6 +25,9 @@ const dossier = (text: string) =>
     referenced_strings: [],
     referenced_names: [],
     basic_blocks: [{ start: "0x1000", end: "0x1001", successors: [] }],
+    native_api: null,
+    native_value_flow: null,
+    limitations: ["The fixture omits native API and value-flow observations."],
   });
 
 const observe = (digit: string, text: string) =>
diff --git a/src/contracts/toolOutputSchemaGroups.ts b/src/contracts/toolOutputSchemaGroups.ts
index 6f38137e6..b381662d0 100644
--- a/src/contracts/toolOutputSchemaGroups.ts
+++ b/src/contracts/toolOutputSchemaGroups.ts
@@ -165,8 +165,8 @@ export const officialOutputSchemas: Readonly> = {
     z.object({
       procedure: procedureIdentitySchema,
       direction: z.enum(["incoming", "outgoing"]),
-      reference_kinds_available: z.boolean().optional(),
-      unresolved_calls: z.array(unresolvedCallSchema).default([]),
+      reference_kinds_available: z.boolean(),
+      unresolved_calls: z.array(unresolvedCallSchema),
       references: z.array(referenceEdgeSchema),
     }),
   ),
diff --git a/src/contracts/toolOutputSchemaPrimitives.ts b/src/contracts/toolOutputSchemaPrimitives.ts
index 2efb498b2..224245c37 100644
--- a/src/contracts/toolOutputSchemaPrimitives.ts
+++ b/src/contracts/toolOutputSchemaPrimitives.ts
@@ -484,11 +484,8 @@ export const procedureInfoOutput = evidenceResultOf(
     length: z.number().min(0),
     signature: nullableText,
     locals: z.array(localVariableSchema),
-    classification: procedureClassificationSchema.nullable().default(null),
-    body: functionBodySchema.default({
-      available: false,
-      reason: "The provider did not report complete function body ranges.",
-    }),
+    classification: procedureClassificationSchema.nullable(),
+    body: functionBodySchema,
   }),
 );
 
diff --git a/src/domain/callPath.test.ts b/src/domain/callPath.test.ts
index 45c48ac3c..00d9e97d4 100644
--- a/src/domain/callPath.test.ts
+++ b/src/domain/callPath.test.ts
@@ -19,6 +19,12 @@ const observe = (
     procedure: {
       address,
       name: `fn_${address.slice(2)}`,
+      classification: null,
+      body: {
+        available: false,
+        reason:
+          "Hopper's public Python API does not expose complete function body ranges",
+      },
       signature: null,
       locals: [],
     },
@@ -29,12 +35,21 @@ const observe = (
     callees: callees.map((callee) => ({
       address: callee,
       name: `fn_${callee.slice(2)}`,
+      classification: null,
+      body: {
+        available: false,
+        reason:
+          "Hopper's public Python API does not expose complete function body ranges",
+      },
     })),
     incoming_references: [],
     outgoing_references: [],
     referenced_strings: [],
     referenced_names: [],
+    native_api: null,
+    native_value_flow: null,
     basic_blocks: [],
+    limitations: [],
   });
   return createEvidence(
     { path: "/tmp/a", sha256: "a".repeat(64), format: "mach-o" },
diff --git a/src/domain/functionComparison.test.ts b/src/domain/functionComparison.test.ts
index 665635c6b..ebc59a6ef 100644
--- a/src/domain/functionComparison.test.ts
+++ b/src/domain/functionComparison.test.ts
@@ -11,6 +11,16 @@ import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
 import { jsonValueSchema } from "./jsonValue.js";
 
 import { compareFunctions } from "./functionComparison.js";
+const procedure = (address: string, name: string) => ({
+  address,
+  name,
+  classification: null,
+  body: {
+    available: false as const,
+    reason:
+      "Hopper's public Python API does not expose complete function body ranges",
+  },
+});
 const dossier = (
   text: string,
   base: "0x1000" | "0x2000",
@@ -18,8 +28,7 @@ const dossier = (
 ) =>
   functionDossierSchema.parse({
     procedure: {
-      address: base,
-      name: "main",
+      ...procedure(base, "main"),
       signature: "int main(void)",
       locals: [],
     },
@@ -32,6 +41,8 @@ const dossier = (
     outgoing_references: [],
     referenced_strings: [],
     referenced_names: [],
+    native_api: null,
+    native_value_flow: null,
     basic_blocks: [
       {
         start: base,
@@ -39,6 +50,7 @@ const dossier = (
         successors,
       },
     ],
+    limitations: [],
   });
 
 const dossierWithReference = (
@@ -52,8 +64,8 @@ const dossierWithReference = (
       {
         source_address: base,
         target_address: target,
-        source_procedure: { address: base, name: "main" },
-        target_procedure: { address: target, name: "helper" },
+        source_procedure: procedure(base, "main"),
+        target_procedure: procedure(target, "helper"),
         kind:
           kind === "unavailable"
             ? { available: false, reason: "provider has no kind authority" }
@@ -111,7 +123,7 @@ describe("function comparison normalized identity", () => {
         functionDossierSchema.parse({
           ...dossier("return 0;", base),
           procedure: {
-            address: base,
+            ...procedure(base, name),
             name,
             signature: "int helper(void)",
             locals: [],
@@ -138,7 +150,7 @@ describe("function comparison normalized identity", () => {
         functionDossierSchema.parse({
           ...dossier("return 0;", base),
           procedure: {
-            address: base,
+            ...procedure(base, name),
             name,
             signature: "int helper(void)",
             locals: [],
@@ -161,7 +173,7 @@ describe("function comparison normalized identity", () => {
     const calling = (base: "0x1000" | "0x2000") =>
       functionDossierSchema.parse({
         ...dossier("return helper();", base),
-        callees: [{ address: base === "0x1000" ? "0x1010" : "0x2010", name }],
+        callees: [procedure(base === "0x1000" ? "0x1010" : "0x2010", name)],
       });
     const result = compareFunctions(
       observe("6", calling("0x1000")),
@@ -174,11 +186,9 @@ describe("function comparison normalized identity", () => {
 });
 
 describe("function collection collation ties", () => {
-  const composed = { address: "0x2000", name: "caf\u00e9" };
-  const decomposed = { address: "0x3000", name: "cafe\u0301" };
-  const calling = (
-    callees: readonly { readonly address: string; readonly name: string }[],
-  ) =>
+  const composed = procedure("0x2000", "caf\u00e9");
+  const decomposed = procedure("0x3000", "cafe\u0301");
+  const calling = (callees: readonly ReturnType[]) =>
     functionDossierSchema.parse({
       ...dossier("return 0;", "0x1000"),
       callees,
@@ -221,10 +231,7 @@ describe("function collection collation ties", () => {
 
   it("uses canonical code-point ordering for collection digests", () => {
     const callees = ["zeta", "Alpha", "alpha", "_helper", "beta"].map(
-      (name, index) => ({
-        address: `0x${(0x2000 + index).toString(16)}`,
-        name,
-      }),
+      (name, index) => procedure(`0x${(0x2000 + index).toString(16)}`, name),
     );
     const canonicalProjection = callees
       .map(({ name }) => ({ direction: "out", name }))
@@ -247,8 +254,8 @@ describe("function collection collation ties", () => {
 });
 
 describe("function comparison ordering controls", () => {
-  const composed = { address: "0x2000", name: "caf\u00e9" };
-  const decomposed = { address: "0x3000", name: "cafe\u0301" };
+  const composed = procedure("0x2000", "caf\u00e9");
+  const decomposed = procedure("0x3000", "cafe\u0301");
 
   it("preserves duplicate Unicode collections and nullable endpoints", () => {
     const controlled = (base: "0x1000" | "0x2000", reverse: boolean) => {
@@ -258,7 +265,7 @@ describe("function comparison ordering controls", () => {
           source_address: base,
           target_address: endpoint,
           source_procedure: null,
-          target_procedure: { address: endpoint, name: "caf\u00e9" },
+          target_procedure: procedure(endpoint, "caf\u00e9"),
           kind: {
             available: true,
             provenance: "provider-reference-manager",
@@ -281,7 +288,7 @@ describe("function comparison ordering controls", () => {
         {
           source_address: base,
           target_address: endpoint,
-          source_procedure: { address: base, name: "dispatch" },
+          source_procedure: procedure(base, "dispatch"),
           target_procedure: null,
           kind: {
             available: true,
@@ -337,7 +344,7 @@ describe("function comparison ordering controls", () => {
       );
     const left = controlled("0x1000", false);
     const right = controlled("0x2000", true);
-    const { native_api: _nativeApi, ...rightWithoutNativeApi } = right;
+    const rightWithoutNativeApi = { ...right, native_api: null };
 
     const comparison = compareFunctions(
       makeEvidence("d", left),
@@ -522,7 +529,7 @@ describe("function comparison", () => {
       functionDossierSchema.parse({
         ...dossier("return 0;", base),
         procedure: {
-          address: base,
+          ...procedure(base, "sub_1000"),
           name: "sub_1000",
           signature: "int helper(void)",
           locals: [],
diff --git a/src/domain/ghidraValues.fixture.ts b/src/domain/ghidraValues.fixture.ts
index 1efd378b3..d0c6d183c 100644
--- a/src/domain/ghidraValues.fixture.ts
+++ b/src/domain/ghidraValues.fixture.ts
@@ -184,6 +184,7 @@ export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
           sequence: 0,
           opcode: "COPY",
           is_dead: false,
+          block_membership: "member",
           inputs: [
             {
               kind: "constant",
@@ -201,6 +202,8 @@ export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
         },
       ],
       def_use: [],
+      parameters: [],
+      parameter_uses: [],
       effects: [],
       truncated: false,
       omitted_operations_lower_bound: 0,
diff --git a/src/domain/hopperValues.test.ts b/src/domain/hopperValues.test.ts
index 2affa2630..c5931cd35 100644
--- a/src/domain/hopperValues.test.ts
+++ b/src/domain/hopperValues.test.ts
@@ -96,13 +96,27 @@ describe("provider-neutral inclusive function body evidence", () => {
     non_contiguous: true,
     contains_entry: true,
   });
-  it("represents missing Hopper extent explicitly as unknown", () => {
+  it("rejects missing provider body metadata", () => {
     expect(
-      procedureIdentitySchema.parse({ address: "0x1000", name: "main" }).body,
-    ).toEqual({
-      available: false,
-      reason: "The provider did not report complete function body ranges.",
-    });
+      procedureIdentitySchema.safeParse({ address: "0x1000", name: "main" })
+        .success,
+    ).toBe(false);
+  });
+  it("rejects segments when required coordinates or unknown permissions are omitted", () => {
+    expect(
+      parseSegments([
+        {
+          name: "__TEXT",
+          start: "0x1",
+          end: "0x2",
+          readable: null,
+          writable: null,
+        },
+      ]).ok,
+    ).toBe(false);
+    expect(
+      parseSegments([{ name: "__TEXT", start: "0x1", end: "0x2" }]).ok,
+    ).toBe(false);
   });
   it("counts inclusive one-byte ranges without assuming an enclosing continuous body", () => {
     expect(
@@ -143,6 +157,7 @@ describe("provider-neutral inclusive function body evidence", () => {
       procedureIdentitySchema.safeParse({
         address: "0x1000",
         name: "external",
+        classification: null,
         body: {
           ...observed(),
           ranges: [],
@@ -159,6 +174,7 @@ describe("provider-neutral inclusive function body evidence", () => {
       procedureIdentitySchema.safeParse({
         address: "0x1002",
         name: "last",
+        classification: null,
         body: observed(),
       }).success,
     ).toBe(true);
@@ -166,6 +182,7 @@ describe("provider-neutral inclusive function body evidence", () => {
       procedureIdentitySchema.safeParse({
         address: "0x1003",
         name: "gap",
+        classification: null,
         body: observed(),
       }).success,
     ).toBe(false);
@@ -173,6 +190,7 @@ describe("provider-neutral inclusive function body evidence", () => {
       procedureIdentitySchema.safeParse({
         address: "other:0x1000",
         name: "other",
+        classification: null,
         body: observed(),
       }).success,
     ).toBe(false);
diff --git a/src/domain/hopperValues.ts b/src/domain/hopperValues.ts
index 366640038..3cbb79c8c 100644
--- a/src/domain/hopperValues.ts
+++ b/src/domain/hopperValues.ts
@@ -52,12 +52,12 @@ const addressedNamesSchema = z.array(
 );
 const addressedNameMapSchema = z.record(z.string(), z.string());
 const segmentSchema = z.object({
-  name: z.string().default(""),
-  start: z.string().default(""),
-  end: z.string().default(""),
-  readable: z.boolean().nullable().default(null),
-  writable: z.boolean().nullable().default(null),
-  executable: z.boolean().nullable().default(null),
+  name: z.string(),
+  start: z.string(),
+  end: z.string(),
+  readable: z.boolean().nullable(),
+  writable: z.boolean().nullable(),
+  executable: z.boolean().nullable(),
 });
 const unavailableAnalysisFactSchema = z
   .object({ available: z.literal(false), reason: z.string() })
@@ -186,12 +186,6 @@ export const functionBodySchema = z.discriminatedUnion("available", [
     }),
 ]);
 
-const unknownFunctionBody = () =>
-  functionBodySchema.default({
-    available: false,
-    reason: "The provider did not report complete function body ranges.",
-  });
-
 /** Check the declared entry membership against complete, inclusive body ranges. */
 export const functionBodyEntryAgrees = (
   body: z.infer,
@@ -226,8 +220,8 @@ export const procedureIdentitySchema = z
   .object({
     address: z.string(),
     name: z.string(),
-    classification: procedureClassificationSchema.nullable().default(null),
-    body: unknownFunctionBody(),
+    classification: procedureClassificationSchema.nullable(),
+    body: functionBodySchema,
   })
   .strict()
   .superRefine((identity, context) => {
@@ -352,9 +346,9 @@ export const functionDossierSchema = z
         })
         .strict(),
     ),
-    native_api: nativeApiBoundarySchema.nullable().default(null),
-    native_value_flow: nativeValueFlowSchema.nullable().default(null),
-    limitations: z.array(z.string()).default([]),
+    native_api: nativeApiBoundarySchema.nullable(),
+    native_value_flow: nativeValueFlowSchema.nullable(),
+    limitations: z.array(z.string()),
   })
   .strict();
 
diff --git a/src/domain/native/nativeValueFlow.ts b/src/domain/native/nativeValueFlow.ts
index 30f2c6219..a4e2a0a4a 100644
--- a/src/domain/native/nativeValueFlow.ts
+++ b/src/domain/native/nativeValueFlow.ts
@@ -18,9 +18,7 @@ export const nativePcodeOperationSchema = z.strictObject({
   sequence: z.number().int().nonnegative(),
   opcode: z.string().min(1),
   is_dead: z.boolean(),
-  block_membership: z
-    .enum(["member", "detached", "unavailable"])
-    .default("unavailable"),
+  block_membership: z.enum(["member", "detached", "unavailable"]),
   inputs: z.array(nativeVarnodeSchema),
   output: nativeVarnodeSchema.nullable(),
 });
@@ -55,24 +53,20 @@ export const nativeValueFlowSchema = z.discriminatedUnion("available", [
     operations: z.array(nativePcodeOperationSchema),
     def_use: z.array(nativePcodeDefUseSchema),
     effects: z.array(nativePcodeEffectSchema),
-    parameters: z
-      .array(
-        z.strictObject({
-          ordinal: z.number().int().nonnegative(),
-          name: z.string(),
-          data_type: z.string(),
-        }),
-      )
-      .default([]),
-    parameter_uses: z
-      .array(
-        z.strictObject({
-          ordinal: z.number().int().nonnegative(),
-          use: z.string(),
-          input_index: z.number().int().nonnegative(),
-        }),
-      )
-      .default([]),
+    parameters: z.array(
+      z.strictObject({
+        ordinal: z.number().int().nonnegative(),
+        name: z.string(),
+        data_type: z.string(),
+      }),
+    ),
+    parameter_uses: z.array(
+      z.strictObject({
+        ordinal: z.number().int().nonnegative(),
+        use: z.string(),
+        input_index: z.number().int().nonnegative(),
+      }),
+    ),
     truncated: z.boolean(),
     omitted_operations_lower_bound: z.number().int().nonnegative(),
     known_omitted_inputs: z.number().int().nonnegative(),
diff --git a/src/domain/reconstructionVerification.functionSources.test.ts b/src/domain/reconstructionVerification.functionSources.test.ts
index 8816a5d48..4c4c04f04 100644
--- a/src/domain/reconstructionVerification.functionSources.test.ts
+++ b/src/domain/reconstructionVerification.functionSources.test.ts
@@ -24,6 +24,12 @@ const dossier = jsonValueSchema.parse(
     procedure: {
       address: "0x1000",
       name: "main",
+      classification: null,
+      body: {
+        available: false,
+        reason:
+          "Hopper's public Python API does not expose complete function body ranges",
+      },
       signature: "int main(void)",
       locals: [],
     },
@@ -36,7 +42,10 @@ const dossier = jsonValueSchema.parse(
     outgoing_references: [],
     referenced_strings: [],
     referenced_names: [],
+    native_api: null,
+    native_value_flow: null,
     basic_blocks: [{ start: "0x1000", end: "0x1001", successors: [] }],
+    limitations: [],
   }),
 );
 
diff --git a/src/ghidra/GhidraFunctionValues.test.ts b/src/ghidra/GhidraFunctionValues.test.ts
index 90f8715d2..6b92d2deb 100644
--- a/src/ghidra/GhidraFunctionValues.test.ts
+++ b/src/ghidra/GhidraFunctionValues.test.ts
@@ -1,6 +1,7 @@
 import { describe, expect, it } from "vitest";
 
 import type { JsonValue } from "../domain/jsonValue.js";
+import { jsonValueSchema } from "../domain/jsonValue.js";
 import { functionDossierSchema } from "../domain/hopperValues.js";
 import {
   parseGhidraFunctionResult,
@@ -37,6 +38,54 @@ describe("Ghidra function-analysis result values", () => {
     },
   );
 
+  it.each(["block_membership", "parameters", "parameter_uses"])(
+    "rejects a value-flow result missing %s",
+    (field) => {
+      const dossier = ghidraFunctionDossier();
+      if (
+        typeof dossier !== "object" ||
+        dossier === null ||
+        Array.isArray(dossier)
+      )
+        throw new TypeError("Ghidra dossier fixture is invalid");
+      const flow = dossier.native_value_flow;
+      if (typeof flow !== "object" || flow === null || Array.isArray(flow))
+        throw new TypeError("Ghidra p-code fixture is invalid");
+      if (!Array.isArray(flow.operations))
+        throw new TypeError("Ghidra operation fixture is invalid");
+      const incompleteFlow =
+        field === "block_membership"
+          ? {
+              ...flow,
+              operations: flow.operations.map((operation, index) =>
+                index !== 0 ||
+                typeof operation !== "object" ||
+                operation === null ||
+                Array.isArray(operation)
+                  ? operation
+                  : Object.fromEntries(
+                      Object.entries(operation).filter(
+                        ([key]) => key !== field,
+                      ),
+                    ),
+              ),
+            }
+          : Object.fromEntries(
+              Object.entries(flow).filter(([key]) => key !== field),
+            );
+
+      expect(
+        parseGhidraFunctionResult(
+          "analyze_function",
+          jsonValueSchema.parse({
+            ...dossier,
+            native_value_flow: incompleteFlow,
+          }),
+        ),
+      ).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
+    },
+  );
+
   it("rejects p-code relationships that refer to omitted operation IDs", () => {
     const dossier = ghidraFunctionDossier();
     if (
diff --git a/src/ida/IdaOperationRunner.ts b/src/ida/IdaOperationRunner.ts
index 8420ff8e9..e775eb864 100644
--- a/src/ida/IdaOperationRunner.ts
+++ b/src/ida/IdaOperationRunner.ts
@@ -426,6 +426,8 @@ export class IdaOperationRunner {
       referenced_strings: [],
       referenced_names: [],
       basic_blocks: [],
+      native_api: null,
+      native_value_flow: null,
       limitations: [
         ...IDA_LIMITATIONS,
         ...this.limitations,
diff --git a/src/ida/IdaSessionClient.test.ts b/src/ida/IdaSessionClient.test.ts
index cf75e5ddc..2b6783c1c 100644
--- a/src/ida/IdaSessionClient.test.ts
+++ b/src/ida/IdaSessionClient.test.ts
@@ -95,6 +95,17 @@ describe("headless IDA producer pagination", () => {
     const dossier = functionDossierSchema.parse(result.value.result);
     expect(dossier.pseudocode).toBe("first line\nsecond line");
     expect(dossier.assembly).toEqual(["0x1000: push rbp", "0x1001: ret"]);
+    expect(dossier).toMatchObject({
+      procedure: {
+        classification: null,
+        body: {
+          available: false,
+          reason: "IDA MCP does not report complete function body ranges.",
+        },
+      },
+      native_api: null,
+      native_value_flow: null,
+    });
     await client.close();
   });
 });
diff --git a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts
index 7662c8234..0da86dfc5 100644
--- a/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts
+++ b/tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts
@@ -35,6 +35,33 @@ const targetObservation = (value: unknown) =>
     ),
   );
 
+const functionDossier = {
+  procedure: {
+    address: "0x1",
+    name: "entry",
+    classification: null,
+    body: {
+      available: false,
+      reason: "The provider did not report complete function body ranges.",
+    },
+    signature: null,
+    locals: [],
+  },
+  pseudocode: "return 0;",
+  assembly: [],
+  comments: [],
+  callers: [],
+  callees: [],
+  incoming_references: [],
+  outgoing_references: [],
+  referenced_strings: [],
+  referenced_names: [],
+  basic_blocks: [],
+  native_api: null,
+  native_value_flow: null,
+  limitations: [],
+};
+
 const fixturePort = (): AnalysisOperationPort => ({
   // oxlint-disable-next-line complexity -- this fixture exhaustively serves the registered MCP surface.
   execute: (name, arguments_) => {
@@ -138,7 +165,16 @@ const fixturePort = (): AnalysisOperationPort => ({
         );
       case "list_segments":
         return Promise.resolve(
-          ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
+          ok([
+            {
+              name: "__TEXT",
+              start: "0x1000",
+              end: "0x2000",
+              readable: null,
+              writable: null,
+              executable: null,
+            },
+          ]),
         );
       case "current_document":
         return Promise.resolve(ok("fixture"));
@@ -151,26 +187,7 @@ const fixturePort = (): AnalysisOperationPort => ({
       case "search_procedures":
         return Promise.resolve(ok(inventory({})));
       case "analyze_function":
-        return Promise.resolve(
-          targetObservation({
-            procedure: {
-              address: "0x1",
-              name: "entry",
-              signature: null,
-              locals: [],
-            },
-            pseudocode: "return 0;",
-            assembly: [],
-            comments: [],
-            callers: [],
-            callees: [],
-            incoming_references: [],
-            outgoing_references: [],
-            referenced_strings: [],
-            referenced_names: [],
-            basic_blocks: [],
-          }),
-        );
+        return Promise.resolve(targetObservation(functionDossier));
       default:
         return Promise.resolve(ok(null));
     }
diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
index 79002f40e..a8c9bf464 100644
--- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
+++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts
@@ -46,8 +46,22 @@ describe("enhanced MCP tools", () => {
           case "list_segments":
             return Promise.resolve(
               ok([
-                { name: "__TEXT", start: "0x1000", end: "0x1800" },
-                { name: "__DATA", start: "0x1800", end: "0x2000" },
+                {
+                  name: "__TEXT",
+                  start: "0x1000",
+                  end: "0x1800",
+                  readable: null,
+                  writable: null,
+                  executable: null,
+                },
+                {
+                  name: "__DATA",
+                  start: "0x1800",
+                  end: "0x2000",
+                  readable: null,
+                  writable: null,
+                  executable: null,
+                },
               ]),
             );
           case "current_document":
@@ -113,6 +127,35 @@ describe("enhanced MCP tools", () => {
       JSON.stringify(parseMcpToolError(result)),
     );
   });
+
+  it("rejects a segment with omitted coordinates instead of reporting zero length", async () => {
+    const client = await connect({
+      execute: (name) =>
+        Promise.resolve(
+          name === "list_segments"
+            ? ok([
+                {
+                  name: "__TEXT",
+                  end: "0x2000",
+                  readable: null,
+                  writable: null,
+                  executable: null,
+                },
+              ])
+            : ok(name === "current_document" ? "fixture" : []),
+        ),
+    });
+    const result = await client.callTool({
+      name: "binary_overview",
+      arguments: {},
+    });
+
+    expect(result.isError).toBe(true);
+    expect(result.content).toContainEqual({
+      type: "text",
+      text: JSON.stringify(parseMcpToolError(result)),
+    });
+  });
 });
 
 const overviewPort = (
@@ -127,7 +170,16 @@ const overviewPort = (
         return Promise.resolve(ok([...documents]));
       case "list_segments":
         return Promise.resolve(
-          ok([{ name: "text", start: "0x1000", end: "0x2000" }]),
+          ok([
+            {
+              name: "text",
+              start: "0x1000",
+              end: "0x2000",
+              readable: null,
+              writable: null,
+              executable: null,
+            },
+          ]),
         );
       default:
         return Promise.resolve(ok([]));
diff --git a/tests/boundary/mcp/enhancedTools.06-rejects-incomplete-function-dossiers-at.test.ts b/tests/boundary/mcp/enhancedTools.06-rejects-incomplete-function-dossiers-at.test.ts
index 212e32824..449432e26 100644
--- a/tests/boundary/mcp/enhancedTools.06-rejects-incomplete-function-dossiers-at.test.ts
+++ b/tests/boundary/mcp/enhancedTools.06-rejects-incomplete-function-dossiers-at.test.ts
@@ -31,6 +31,38 @@ describe("analyze_function MCP producer validation", () => {
     });
   });
 
+  it.each([
+    "procedure.classification",
+    "procedure.body",
+    "native_api",
+    "native_value_flow",
+    "limitations",
+  ])("rejects a complete dossier missing %s", async (field) => {
+    const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
+    const value = structuredClone(dossier) as unknown as Record<
+      string,
+      unknown
+    >;
+    if (field.startsWith("procedure.")) {
+      const procedure = value.procedure as Record;
+      delete procedure[field.slice("procedure.".length)];
+    } else delete value[field];
+
+    const client = await connect({
+      execute: () => Promise.resolve(observed(value)),
+    });
+    const result = await client.callTool({
+      name: "analyze_function",
+      arguments: { procedure: "0x1" },
+    });
+
+    expect(result.isError).toBe(true);
+    expect(result.content).toContainEqual({
+      type: "text",
+      text: JSON.stringify(parseMcpToolError(result)),
+    });
+  });
+
   it("rejects a malformed collection in an otherwise complete dossier", async () => {
     const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
     const client = await connect({
diff --git a/tests/boundary/mcp/investigationAnalysisMcp.test.ts b/tests/boundary/mcp/investigationAnalysisMcp.test.ts
index 752f81bc3..a1259e667 100644
--- a/tests/boundary/mcp/investigationAnalysisMcp.test.ts
+++ b/tests/boundary/mcp/investigationAnalysisMcp.test.ts
@@ -129,7 +129,15 @@ const dossierWithCallees = (addresses: readonly string[]) => {
       parameters: base.parameters,
       result: jsonValueSchema.parse({
         ...jsonObjectSchema.parse(base.normalized_result),
-        callees: addresses.map((address) => ({ address, name: "next" })),
+        callees: addresses.map((address) => ({
+          address,
+          name: "next",
+          classification: null,
+          body: {
+            available: false,
+            reason: "The fixture has no callee body-extent observation.",
+          },
+        })),
       }),
       rawResult: base.raw_result,
       confidence: base.confidence,
diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts
index 1282aef36..832b55e40 100644
--- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts
+++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts
@@ -308,7 +308,16 @@ const makeProvider = (
             operation === "health"
               ? null
               : operation === "list_segments"
-                ? [{ name: "__TEXT", start: "0x1000", end: "0x2000" }]
+                ? [
+                    {
+                      name: "__TEXT",
+                      start: "0x1000",
+                      end: "0x2000",
+                      readable: null,
+                      writable: null,
+                      executable: null,
+                    },
+                  ]
                 : operation === "list_documents"
                   ? ["fixture"]
                   : operation === "list_procedures"
diff --git a/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts b/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts
index 871ee140f..515172eab 100644
--- a/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts
+++ b/tests/boundary/providers/hopper/hopperBridgeFacade.test.ts
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
 import { describe, expect, it } from "vitest";
 import { z } from "zod";
 import { OFFICIAL_TOOL_CONTRACTS } from "../../../../src/contracts/officialToolContracts.js";
+import { functionDossierSchema } from "../../../../src/domain/hopperValues.js";
 
 const execute = promisify(execFile);
 const bridgePath = new URL(
@@ -48,6 +49,7 @@ const probeResultSchema = z.strictObject({
       reason: z.string(),
     }),
   }),
+  analyze_function: z.unknown(),
   procedure_references: z.strictObject({
     procedure: z.strictObject({
       address: z.literal("0x401000"),
@@ -153,6 +155,19 @@ describe("Hopper API facade", () => {
       if (!parsed.success) throw new Error(`${name}: ${parsed.error.message}`);
       expect(parsed.success, name).toBe(true);
     }
+    const dossier = functionDossierSchema.parse(result.analyze_function);
+    expect(dossier).toMatchObject({
+      procedure: {
+        classification: null,
+        body: {
+          available: false,
+          reason:
+            "Hopper's public Python API does not expose complete function body ranges",
+        },
+      },
+      native_api: null,
+      native_value_flow: null,
+    });
     expect(result.provider_faults.map((reply) => reply.error.message)).toEqual([
       "TypeError: Hopper bridge operation failed",
       "ValueError: Hopper bridge operation failed",
diff --git a/tests/composition/directAnalysisSnapshotReplay.test.ts b/tests/composition/directAnalysisSnapshotReplay.test.ts
index da6d3a11b..7da4ec8cf 100644
--- a/tests/composition/directAnalysisSnapshotReplay.test.ts
+++ b/tests/composition/directAnalysisSnapshotReplay.test.ts
@@ -71,6 +71,11 @@ const functionDossier = {
   procedure: {
     address: "0x1000",
     name: "fixture",
+    classification: null,
+    body: {
+      available: false,
+      reason: "The provider did not report complete function body ranges.",
+    },
     signature: null,
     locals: [],
   },
@@ -171,7 +176,16 @@ const makeProvider = (
           trace.calls.push(operation);
           const results: Readonly> = {
             health: null,
-            list_segments: [{ name: "__TEXT", start: "0x1000", end: "0x2000" }],
+            list_segments: [
+              {
+                name: "__TEXT",
+                start: "0x1000",
+                end: "0x2000",
+                readable: null,
+                writable: null,
+                executable: null,
+              },
+            ],
             list_documents: ["fixture"],
             list_procedures: ["0x1000"],
             list_strings: { "0x1000": "fixture" },
diff --git a/tests/fixtures/hopperBridgeFacadeProbe.py b/tests/fixtures/hopperBridgeFacadeProbe.py
index 195292136..fa1cacefa 100644
--- a/tests/fixtures/hopperBridgeFacadeProbe.py
+++ b/tests/fixtures/hopperBridgeFacadeProbe.py
@@ -57,6 +57,12 @@ class FakeReferenceSegment:
     def getReferencesOfAddress(self, address):
         return []
 
+    def getCommentAtAddress(self, address):
+        return None
+
+    def getInlineCommentAtAddress(self, address):
+        return None
+
 
 class FakeProcedure:
     def __init__(self, segment):
@@ -86,6 +92,12 @@ class FakeProcedure:
     def getAllCallees(self):
         return []
 
+    def getAllCallerProcedures(self):
+        return []
+
+    def getAllCalleeProcedures(self):
+        return []
+
 
 class FakeBlock:
     def getStartingAddress(self):
@@ -93,6 +105,9 @@ class FakeBlock:
 
     def getEndingAddress(self):
         return 0x401004
+
+    def getSuccessorCount(self):
+        return 0
 def load_bridge(path):
     namespace = {
         "__file__": path,
@@ -184,6 +199,14 @@ def main():
     procedure_info = bridge["_dispatch"](
         "procedure_info", {"procedure": "0x401000"}
     )
+    bridge["_assembly"] = lambda procedure: "ret"
+    bridge["_pseudocode"] = lambda document, procedure: None
+    bridge["_native_calls"] = lambda procedure, direction: ({}, [])
+    bridge["_string_inventory"] = lambda document, targets=None: {}
+    bridge["_search_inventory"] = lambda document, kind: []
+    analyze_function = bridge["_dispatch"](
+        "analyze_function", {"procedure": "0x401000"}
+    )
     provider_faults = []
     for error_type in (TypeError, ValueError, KeyError):
         FakeDocumentProvider.current.address_error = error_type("credential=supersecret")
@@ -236,6 +259,7 @@ def main():
                 "containing_procedure": containing_procedure,
                 "procedure_references": procedure_references,
                 "procedure_info": procedure_info,
+                "analyze_function": analyze_function,
                 "provider_faults": provider_faults,
                 "malformed_requests": malformed_requests,
                 "session_document_reused": selected,

From 08daf056cc8e4d092f9592574d09d5182457b7bc Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 03:06:04 +0800
Subject: [PATCH 070/189] fix(cli): classify JSON input permission denials

---
 src/cliJsonInput.ts                           | 30 ++++++++++++++++
 tests/boundary/cli/jsonInputStatus.test.ts    |  8 ++++-
 .../boundary/filesystem/cliJsonInput.test.ts  | 35 ++++++++++++++-----
 3 files changed, 64 insertions(+), 9 deletions(-)

diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts
index a47d1e5f5..6b3947ffc 100644
--- a/src/cliJsonInput.ts
+++ b/src/cliJsonInput.ts
@@ -7,6 +7,7 @@ import {
 } from "./application/RegularFileRead.js";
 import { parseUtf8Json } from "./application/Utf8JsonInput.js";
 import {
+  AnalysisAccessDeniedError,
   AnalysisInputError,
   AnalysisResourceConstraintError,
 } from "./domain/analysisErrorCore.js";
@@ -49,6 +50,9 @@ export const parseCliJsonInput = async (
           input_reason: "too-large",
         },
       };
+    const systemCode = accessDeniedSystemCode(cause);
+    if (systemCode !== undefined)
+      return jsonAccessDeniedError(value, operation, systemCode, cause);
     if (
       ["{", "["].includes(value.trimStart()[0] ?? "") &&
       cannotBeAnExistingFile(cause) &&
@@ -59,6 +63,15 @@ export const parseCliJsonInput = async (
   }
 };
 
+const accessDeniedSystemCode = (
+  cause: unknown,
+): "EACCES" | "EPERM" | undefined => {
+  if (!(cause instanceof Error) || !("code" in cause)) return undefined;
+  return cause.code === "EACCES" || cause.code === "EPERM"
+    ? cause.code
+    : undefined;
+};
+
 /**
  * Resolve named string fields of CLI-supplied JSON against the operator
  * working directory. Each entry is a key path from the document root; only
@@ -148,6 +161,23 @@ const jsonFileError = (
   },
 });
 
+const jsonAccessDeniedError = (
+  path: string,
+  operation: string,
+  systemCode: "EACCES" | "EPERM",
+  cause: unknown,
+) => ({
+  ok: false as const,
+  error: {
+    error: "Application workflow failed",
+    ...projectAnalysisError(
+      new AnalysisAccessDeniedError(operation, path, systemCode, { cause }),
+    ),
+    input_path: path,
+    input_reason: "read-failed" as const,
+  },
+});
+
 /** Preserve file-selection and system failures alongside the requested path. */
 const readFailureIssue = (path: string | undefined, cause: unknown) => {
   const code =
diff --git a/tests/boundary/cli/jsonInputStatus.test.ts b/tests/boundary/cli/jsonInputStatus.test.ts
index 7e768d7ec..bd5033f2c 100644
--- a/tests/boundary/cli/jsonInputStatus.test.ts
+++ b/tests/boundary/cli/jsonInputStatus.test.ts
@@ -247,9 +247,15 @@ describe("compiled CLI JSON path ambiguity", () => {
         });
 
         expect(result.json).toMatchObject({
-          code: "invalid_request",
+          code: "access_denied",
           input_path: input,
           input_reason: "read-failed",
+          details: {
+            operation: "capture_browser_scenario",
+            path: input,
+            system_code: "EACCES",
+            boundary: "filesystem-read",
+          },
         });
         expect(result.exitCode).toBe(1);
       } finally {
diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts
index e550f88b8..9a8c93d89 100644
--- a/tests/boundary/filesystem/cliJsonInput.test.ts
+++ b/tests/boundary/filesystem/cliJsonInput.test.ts
@@ -13,12 +13,25 @@ import { promisify } from "node:util";
 
 import { describe, expect, it, onTestFinished } from "vitest";
 
+import { createCli } from "../../../src/cli.js";
 import { isCliOperationFailure } from "../../../src/cliLogging.js";
 import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
 import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js";
 import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
 import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
 
+const runCli = async (arguments_: readonly string[]): Promise => {
+  let stdout = "";
+  await createCli({}).serve([...arguments_, "--json"], {
+    env: {},
+    stdout: (chunk) => {
+      stdout += chunk;
+    },
+    exit: () => undefined,
+  });
+  return JSON.parse(stdout) as unknown;
+};
+
 describe("CLI JSON file selection", () => {
   it("accepts a symlink to a regular JSON file", async () => {
     const root = await createTestTempDirectory("rea-json-input-symlink-");
@@ -219,21 +232,27 @@ describe("CLI JSON input", () => {
   );
 
   it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
-    "lists a permission denial as the cause of an unreadable file",
+    "projects a real permission denial as access_denied",
     async () => {
       const root = await createTestTempDirectory("rea-json-input-denied-");
       const path = join(root, "input.json");
       await writeFile(path, "{}");
       await chmod(path, 0o000);
       onTestFinished(() => chmod(path, 0o600));
-      expect(await parseCliJsonInput(path, "test-input")).toMatchObject({
-        ok: false,
-        error: {
-          input_reason: "read-failed",
-          details: {
-            issues: [{ message: expect.stringContaining("(EACCES)") }],
-          },
+      const result = await runCli(["inspect-analysis-view", path]);
+      expect(analysisCliErrorEnvelopeSchema.parse(result)).toMatchObject({
+        error: "Application workflow failed",
+        code: "access_denied",
+        category: "unavailable",
+        details: {
+          operation: "inspect-analysis-view",
+          path,
+          system_code: "EACCES",
+          boundary: "filesystem-read",
         },
+        input_path: path,
+        input_reason: "read-failed",
+        remediation: { action: expect.stringContaining("read access") },
       });
     },
   );

From 55a46f7c7176075c9edda4fe61ed995f2ceadf6a Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Sat, 10 Oct 2026 03:11:08 +0800
Subject: [PATCH 071/189] fix(javascript): resolve query-only HTML references
 to their document

---
 .../JavaScriptArtifactPathResolution.ts       | 28 +++++-
 .../JavaScriptHtmlBaseResolution.test.ts      | 22 +++++
 .../javascriptHtmlReferenceResolution.test.ts | 99 +++++++++++++++++++
 3 files changed, 144 insertions(+), 5 deletions(-)
 create mode 100644 tests/composition/javascript-applications/javascriptHtmlReferenceResolution.test.ts

diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts
index b5ba5847b..c28cd45c5 100644
--- a/src/application/javascript/JavaScriptArtifactPathResolution.ts
+++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts
@@ -270,7 +270,9 @@ const htmlCandidate = (
     ]);
   if (declaredPath.startsWith("/")) return declaredPath.slice(1);
   if (base === undefined || base === null || base === "")
-    return posix.join(posix.dirname(input.sourcePath), declaredPath);
+    return declaredPath === ""
+      ? input.sourcePath
+      : posix.join(posix.dirname(input.sourcePath), declaredPath);
   // A local base href is a second untrusted path input; apply the same
   // admission rules a declared path gets so it cannot smuggle traversal or
   // separator syntax past canonicalization.
@@ -286,23 +288,39 @@ const htmlCandidate = (
   const basePath = decodedBase.startsWith("/")
     ? decodedBase.slice(1)
     : posix.join(posix.dirname(input.sourcePath), decodedBase);
+  if (declaredPath === "")
+    return emptyHtmlReference(input, decodedBase, basePath);
   return posix.join(htmlBaseDirectory(decodedBase, basePath), declaredPath);
 };
 
+const emptyHtmlReference = (
+  input: ResolveArtifactPathInput,
+  base: string,
+  basePath: string,
+): string | ArtifactPathResolution => {
+  if (!htmlBaseIsDirectory(base)) return basePath;
+  const confined = confineCandidate(input, basePath);
+  if (typeof confined !== "string") return confined;
+  return unresolvedOutcome(input, "not-found", [
+    `The HTML reference resolves to directory ${confined || "."}, not an exact selected application file.`,
+  ]);
+};
+
 /**
  * The directory a relative HTML reference resolves against. A base path
  * ending in "/" or in a "." or ".." segment is already a directory, because a
  * relative reference resolves against the base URL's directory and those
  * segments are dropped rather than stepped through.
  */
-const htmlBaseDirectory = (base: string, basePath: string): string =>
+const htmlBaseIsDirectory = (base: string): boolean =>
   base.endsWith("/") ||
   base.endsWith("/.") ||
   base.endsWith("/..") ||
   base === "." ||
-  base === ".."
-    ? basePath
-    : posix.dirname(basePath);
+  base === "..";
+
+const htmlBaseDirectory = (base: string, basePath: string): string =>
+  htmlBaseIsDirectory(base) ? basePath : posix.dirname(basePath);
 
 const confineCandidate = (
   input: ResolveArtifactPathInput,
diff --git a/src/application/javascript/JavaScriptHtmlBaseResolution.test.ts b/src/application/javascript/JavaScriptHtmlBaseResolution.test.ts
index 681d79099..1da6539a0 100644
--- a/src/application/javascript/JavaScriptHtmlBaseResolution.test.ts
+++ b/src/application/javascript/JavaScriptHtmlBaseResolution.test.ts
@@ -33,6 +33,28 @@ const resolve = (declaredPath: string, htmlBaseHref: string) =>
   });
 const documentUrl = "https://artifact.test/renderer/index.html";
 describe("HTML base href URL components", () => {
+  it.each(["?base=1", "#base-fragment"])(
+    "keeps the document pathname for suffix-only base href %s",
+    (base) => {
+      const resolvedBase = new URL(base, documentUrl);
+      expect(new URL("app.js", resolvedBase).pathname).toBe("/renderer/app.js");
+      expect(resolve("app.js", base)).toMatchObject({
+        resolved_path: "renderer/app.js",
+        resolution_status: "resolved",
+      });
+
+      const emptyPathReference = "?script=1#fragment";
+      expect(new URL(emptyPathReference, resolvedBase).pathname).toBe(
+        "/renderer/index.html",
+      );
+      expect(resolve(emptyPathReference, base)).toMatchObject({
+        declared_path: emptyPathReference,
+        resolved_path: "renderer/index.html",
+        resolution_status: "resolved",
+      });
+    },
+  );
+
   it.each([
     "/assets/?cache=/wrong/",
     "/assets/#/wrong/",
diff --git a/tests/composition/javascript-applications/javascriptHtmlReferenceResolution.test.ts b/tests/composition/javascript-applications/javascriptHtmlReferenceResolution.test.ts
new file mode 100644
index 000000000..00265773b
--- /dev/null
+++ b/tests/composition/javascript-applications/javascriptHtmlReferenceResolution.test.ts
@@ -0,0 +1,99 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+it("resolves empty-path HTML script URLs against their canonical base path", async () => {
+  const root = await createTestTempDirectory("rea-html-empty-reference-");
+  await Promise.all([
+    mkdir(join(root, "base-file", "assets"), { recursive: true }),
+    mkdir(join(root, "base-directory", "assets"), { recursive: true }),
+    mkdir(join(root, "escaped"), { recursive: true }),
+  ]);
+  await Promise.all([
+    writeFile(
+      join(root, "document.html"),
+      '',
+    ),
+    writeFile(
+      join(root, "base-file", "index.html"),
+      '',
+    ),
+    writeFile(join(root, "base-file", "assets", "entry.html"), "
"), + writeFile( + join(root, "base-directory", "index.html"), + '', + ), + writeFile( + join(root, "base-directory", "assets", "index.js"), + "export const value = 1;", + ), + writeFile( + join(root, "escaped", "index.html"), + '', + ), + ]); + + const result = await reconstructJavaScriptArtifact({ + input_path: root, + format: "directory", + }); + const graph = result.graph; + const loadFor = (scriptPath: string) => + graph.edges.find( + (edge) => + edge.relation === "loads" && edge.properties.script_path === scriptPath, + ); + const targetPath = (edge: NonNullable>) => + graph.nodes + .find(({ node_id }) => node_id === edge.target_node_id) + ?.observations.find( + ({ properties }) => typeof properties.path === "string", + )?.properties.path; + const unresolvedReference = (scriptPath: string) => + graph.nodes + .flatMap(({ observations }) => observations) + .find( + ({ properties }) => + properties.mechanism === "html-script-reference" && + properties.script_path === scriptPath, + )?.properties; + + for (const scriptPath of ["?document=1", "#document-fragment"]) { + const edge = loadFor(scriptPath); + expect(edge).toMatchObject({ + properties: { + script_path: scriptPath, + resolved_path: "document.html", + resolution_status: "resolved", + }, + }); + if (edge !== undefined) expect(targetPath(edge)).toBe("document.html"); + } + + const baseFileEdge = loadFor("?base-file=1#script-fragment"); + expect(baseFileEdge).toMatchObject({ + properties: { + script_path: "?base-file=1#script-fragment", + base_href: "assets/entry.html?base=1#base-fragment", + resolved_path: "base-file/assets/entry.html", + resolution_status: "resolved", + }, + }); + if (baseFileEdge !== undefined) + expect(targetPath(baseFileEdge)).toBe("base-file/assets/entry.html"); + + expect(unresolvedReference("?base-directory=1")).toMatchObject({ + resolution_status: "not-found", + limitations: [expect.stringContaining("resolves to directory")], + }); + expect(unresolvedReference("?escape=1")).toMatchObject({ + resolution_status: "rejected", + limitations: [ + expect.stringContaining("escapes the canonical artifact root"), + ], + }); +}); From 218c13160ec0ed7116d6633fc76559ec39dae4d7 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:07:12 +0800 Subject: [PATCH 072/189] fix: report malformed application evidence as input errors --- .../ReconstructionObligationCandidates.ts | 9 +- .../JavaScriptApplicationEvidenceGraph.ts | 300 ++++++++++++++---- .../JavaScriptApplicationWorkflowService.ts | 132 ++++---- .../JavaScriptRuntimeReconciliationService.ts | 1 - .../JavaScriptSemanticTraceService.ts | 36 ++- src/domain/evidence.ts | 20 +- src/domain/evidenceBundle.ts | 15 +- .../filesystem/evidenceBundleFiles.test.ts | 2 +- .../javascriptApplicationWorkflows.test.ts | 11 +- .../javascriptExportContainerCoverage.test.ts | 4 +- .../javascriptExportShapeComparison.test.ts | 4 +- .../javascriptRequireLiteralPaths.test.ts | 4 +- .../filesystem/sourceToBundlePaths.test.ts | 17 +- .../javascriptSemanticTraceEvidence.test.ts | 221 +++++++++++++ .../processComparisonDiagnosticsMcp.test.ts | 2 +- 15 files changed, 613 insertions(+), 165 deletions(-) create mode 100644 tests/boundary/javascriptSemanticTraceEvidence.test.ts diff --git a/src/application/ReconstructionObligationCandidates.ts b/src/application/ReconstructionObligationCandidates.ts index b01f88d7e..e09952769 100644 --- a/src/application/ReconstructionObligationCandidates.ts +++ b/src/application/ReconstructionObligationCandidates.ts @@ -76,7 +76,14 @@ const deriveApplicationCandidates = ( ) return; try { - const source = parseApplicationGraphEvidence(evidence); + const parsed = parseApplicationGraphEvidence(evidence); + if (!parsed.ok) { + limitations.add( + `Application Evidence ${evidence.evidence_id} could not generate candidates because it failed graph validation.`, + ); + return; + } + const source = parsed.value; for (const node of source.graph.nodes) { const candidatePolicy = applicationObligationPolicy(node.kind); if (candidatePolicy === undefined) { diff --git a/src/application/javascript/JavaScriptApplicationEvidenceGraph.ts b/src/application/javascript/JavaScriptApplicationEvidenceGraph.ts index 459c226ac..3a42ce32e 100644 --- a/src/application/javascript/JavaScriptApplicationEvidenceGraph.ts +++ b/src/application/javascript/JavaScriptApplicationEvidenceGraph.ts @@ -8,6 +8,13 @@ import { parseEvidence, type Evidence, } from "../../domain/evidence.js"; +import { + type AnalysisInputIssue, + AnalysisInputError, +} from "../../domain/analysisErrorCore.js"; +import { projectInputIssues } from "../../domain/inputIssueProjection.js"; +import { err, ok, type Result } from "../../domain/result.js"; +import { z } from "zod"; import { analyzeJavaScriptApplicationInputSchema, javascriptApplicationAnalysisResultSchema, @@ -30,6 +37,24 @@ export interface ApplicationGraphEvidenceSource { readonly semanticGraph: JavaScriptSemanticGraph | null; } +/** Caller-owned Evidence failed validation at the application graph boundary. */ +export interface ApplicationGraphEvidenceInputFailure { + readonly issues: readonly AnalysisInputIssue[]; +} + +/** Convert typed parser issues into this workflow's caller-facing input error. */ +export const applicationGraphEvidenceInputError = ( + operation: string, + failure: ApplicationGraphEvidenceInputFailure, +): AnalysisInputError => + new AnalysisInputError(operation, undefined, failure.issues); + +class InvalidApplicationGraphEvidence extends Error { + constructor(readonly issues: readonly AnalysisInputIssue[]) { + super("Application graph Evidence failed input validation"); + } +} + const ownedApplicationSources = new WeakMap< Evidence, ApplicationGraphEvidenceSource @@ -51,7 +76,7 @@ export const rememberOwnedApplicationGraphEvidence = ( ); ownedApplicationSources.set( evidence, - Object.freeze(staticApplicationSourceForResult(evidence, result)), + Object.freeze(staticApplicationSourceForResult(evidence, result, [])), ); return evidence; }; @@ -59,62 +84,79 @@ export const rememberOwnedApplicationGraphEvidence = ( /** Parse and authenticate one REA-produced JavaScript Application Graph Evidence. */ export const parseApplicationGraphEvidence = ( input: unknown, -): ApplicationGraphEvidenceSource => { - const evidence = parseEvidence(input); - const owned = ownedApplicationSources.get(evidence); - if (owned !== undefined) return owned; - if ( - evidence.operation === "analyze_javascript_application" && - evidence.predicate_type === "rea.javascript-application-analysis" && - providerMatches(evidence, JAVASCRIPT_APPLICATION_PROVIDER) - ) - return staticApplicationSource(evidence); - if ( - evidence.operation === "reconcile_javascript_runtime" && - evidence.predicate_type === "rea.javascript-runtime-reconciliation" && - providerMatches(evidence, JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER) - ) - return staticRuntimeSource(evidence); - if ( - evidence.operation === "project_managed_application_graph" && - evidence.predicate_type === "rea.managed-application-graph" && - providerMatches(evidence, MANAGED_WORKFLOW_PROVIDER) - ) - return managedApplicationSource(evidence); - throw new TypeError( - "Application workflow requires authenticated analyze_javascript_application, reconcile_javascript_runtime, or project_managed_application_graph Evidence", - ); -}; + path: readonly (string | number)[] = [], +): Result< + ApplicationGraphEvidenceSource, + ApplicationGraphEvidenceInputFailure +> => + captureInputValidation(() => { + const evidence = parseEvidenceInput(input, path); + const owned = ownedApplicationSources.get(evidence); + if (owned !== undefined) return owned; + if (evidence.operation === "analyze_javascript_application") { + requirePredicate(evidence, "rea.javascript-application-analysis", path); + requireProvider(evidence, JAVASCRIPT_APPLICATION_PROVIDER, path); + return staticApplicationSource(evidence, path); + } + if (evidence.operation === "reconcile_javascript_runtime") { + requirePredicate(evidence, "rea.javascript-runtime-reconciliation", path); + requireProvider( + evidence, + JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER, + path, + ); + return staticRuntimeSource(evidence, path); + } + if (evidence.operation === "project_managed_application_graph") { + requirePredicate(evidence, "rea.managed-application-graph", path); + requireProvider(evidence, MANAGED_WORKFLOW_PROVIDER, path); + return managedApplicationSource(evidence, path); + } + throw invalidEvidence( + path, + "operation", + "Expected authenticated JavaScript analysis, runtime reconciliation, or managed application graph Evidence.", + ); + }); const staticApplicationSource = ( evidence: Evidence, + path: readonly (string | number)[], ): ApplicationGraphEvidenceSource => { - const result = javascriptApplicationAnalysisResultSchema.parse( + const result = parseCallerValue( + (input) => javascriptApplicationAnalysisResultSchema.parse(input), evidence.normalized_result, + [...path, "normalized_result"], ); - return staticApplicationSourceForResult(evidence, result); + return staticApplicationSourceForResult(evidence, result, path); }; const staticApplicationSourceForResult = ( evidence: Evidence, result: JavaScriptApplicationAnalysisResult, + path: readonly (string | number)[], ): ApplicationGraphEvidenceSource => { if ( evidence.authority !== "shipped-artifact" || evidence.confidence !== "derived" ) - throw new TypeError( - "JavaScript application Evidence authority or confidence is invalid", + throw invalidEvidence( + path, + "authority", + "JavaScript application Evidence must use shipped-artifact authority and derived confidence.", ); if (evidence.predicate_type !== "rea.javascript-application-analysis") - throw new TypeError( - "JavaScript application Evidence predicate does not match its result shape", + throw invalidEvidence( + path, + "predicate_type", + "JavaScript application Evidence predicate does not match its result shape.", ); - analyzeJavaScriptApplicationInputSchema.parse({ - input_path: result.input_path, - ...evidence.parameters, - }); - assertApplicationSubject(evidence, result); + parseCallerValue( + (input) => analyzeJavaScriptApplicationInputSchema.parse(input), + { input_path: result.input_path, ...evidence.parameters }, + [...path, "parameters"], + ); + assertApplicationSubject(evidence, result, path); return { evidence, graph: result.graph, @@ -126,30 +168,40 @@ const staticApplicationSourceForResult = ( const staticRuntimeSource = ( evidence: Evidence, + path: readonly (string | number)[], ): ApplicationGraphEvidenceSource => { if ( evidence.authority !== "analyst-inference" || evidence.confidence !== "inferred" ) - throw new TypeError( - "JavaScript runtime reconciliation Evidence authority or confidence is invalid", + throw invalidEvidence( + path, + "authority", + "Runtime reconciliation Evidence must use analyst-inference authority and inferred confidence.", ); - const result = javascriptRuntimeReconciliationResultSchema.parse( + const result = parseCallerValue( + (input) => javascriptRuntimeReconciliationResultSchema.parse(input), evidence.normalized_result, + [...path, "normalized_result"], ); - if ( - result.evidence_links.some( - (evidenceId) => !evidence.evidence_links.includes(evidenceId), - ) - ) - throw new TypeError( - "Runtime reconciliation result references Evidence outside its envelope", + const unmatchedLink = result.evidence_links.find( + (evidenceId) => !evidence.evidence_links.includes(evidenceId), + ); + if (unmatchedLink !== undefined) + throw invalidEvidence( + [...path, "normalized_result"], + "evidence_links", + `Runtime reconciliation result references Evidence ${unmatchedLink} outside its envelope.`, ); const applicationLayer = result.static_layers.find( ({ role }) => role === "application", ); if (applicationLayer === undefined) - throw new TypeError("Runtime reconciliation application layer is missing"); + throw invalidEvidence( + [...path, "normalized_result"], + "static_layers", + "Runtime reconciliation Evidence must include its application layer.", + ); return { evidence, graph: result.graph, @@ -161,24 +213,30 @@ const staticRuntimeSource = ( const managedApplicationSource = ( evidence: Evidence, + path: readonly (string | number)[], ): ApplicationGraphEvidenceSource => { if ( evidence.authority !== "analyst-inference" || evidence.confidence !== "inferred" ) - throw new TypeError( - "Managed application graph Evidence authority or confidence is invalid", + throw invalidEvidence( + path, + "authority", + "Managed application graph Evidence must use analyst-inference authority and inferred confidence.", ); - const result = managedApplicationGraphResultSchema.parse( + const result = parseCallerValue( + (input) => managedApplicationGraphResultSchema.parse(input), evidence.normalized_result, + [...path, "normalized_result"], ); - if ( - result.evidence_links.some( - (evidenceId) => !evidence.evidence_links.includes(evidenceId), - ) - ) - throw new TypeError( - "Managed application graph result references Evidence outside its envelope", + const unmatchedLink = result.evidence_links.find( + (evidenceId) => !evidence.evidence_links.includes(evidenceId), + ); + if (unmatchedLink !== undefined) + throw invalidEvidence( + [...path, "normalized_result"], + "evidence_links", + `Managed application graph result references Evidence ${unmatchedLink} outside its envelope.`, ); return { evidence, @@ -192,6 +250,7 @@ const managedApplicationSource = ( const assertApplicationSubject = ( evidence: Evidence, result: JavaScriptApplicationAnalysisResult, + path: readonly (string | number)[], ): void => { if ( evidence.subject === null || @@ -199,8 +258,10 @@ const assertApplicationSubject = ( evidence.subject.format !== result.format || evidence.subject.local_path !== result.input_path ) - throw new TypeError( - "JavaScript application Evidence subject does not match its result", + throw invalidEvidence( + path, + "subject", + "JavaScript application Evidence subject must match the analyzed artifact identity and input path.", ); }; @@ -216,15 +277,116 @@ const providerMatches = ( evidence.provider.name === provider.name && evidence.provider.version === provider.version; +const requirePredicate = ( + evidence: Evidence, + expected: string, + path: readonly (string | number)[], +): void => { + if (evidence.predicate_type !== expected) + throw invalidEvidence( + path, + "predicate_type", + `Expected predicate ${expected} for operation ${evidence.operation}.`, + ); +}; + +const requireProvider = ( + evidence: Evidence, + expected: { + readonly id: string; + readonly name: string; + readonly version: string; + }, + path: readonly (string | number)[], +): void => { + if (!providerMatches(evidence, expected)) + throw invalidEvidence( + path, + "provider", + `Expected provider ${expected.id} v${expected.version} for operation ${evidence.operation}.`, + ); +}; + /** Parse unique, artifact-bound Evidence that may extend a native handoff. */ export const parseNativeApplicationEvidence = ( inputs: readonly unknown[], -): Evidence[] => { - const parsed = inputs.map((input) => parseEvidence(input)); - if (parsed.some(({ subject }) => subject === null)) - throw new TypeError("Native handoff Evidence requires an artifact subject"); - const ids = parsed.map(({ evidence_id: id }) => id); - if (new Set(ids).size !== ids.length) - throw new TypeError("Native handoff Evidence must be unique"); - return parsed; + path: readonly (string | number)[] = [], +): Result => + captureInputValidation(() => { + const parsed = inputs.map((input, index) => + parseEvidenceInput(input, [...path, index]), + ); + const withoutSubject = parsed.findIndex(({ subject }) => subject === null); + if (withoutSubject !== -1) + throw invalidEvidence( + [...path, withoutSubject], + "subject", + "Native handoff Evidence requires an artifact subject.", + ); + const ids = parsed.map(({ evidence_id: id }) => id); + if (new Set(ids).size !== ids.length) + throw invalidEvidence( + path, + "evidence_id", + "Native handoff Evidence must be unique.", + ); + return parsed; + }); + +const captureInputValidation = ( + operation: () => Value, +): Result => { + try { + return ok(operation()); + } catch (cause: unknown) { + if (cause instanceof InvalidApplicationGraphEvidence) + return err({ issues: cause.issues }); + throw cause; + } }; + +const parseEvidenceInput = ( + input: unknown, + path: readonly (string | number)[], +): Evidence => { + try { + return parseEvidence(input); + } catch (cause: unknown) { + if (cause instanceof z.ZodError) throw zodInputFailure(cause, input, path); + throw cause; + } +}; + +const parseCallerValue = ( + parse: (input: unknown) => Value, + input: unknown, + path: readonly (string | number)[], +): Value => { + try { + return parse(input); + } catch (cause: unknown) { + if (cause instanceof z.ZodError) throw zodInputFailure(cause, input, path); + throw cause; + } +}; + +const zodInputFailure = ( + cause: z.ZodError, + input: unknown, + path: readonly (string | number)[], +): InvalidApplicationGraphEvidence => + new InvalidApplicationGraphEvidence( + projectInputIssues(cause.issues, input).map((issue) => ({ + ...issue, + path: [...path, ...issue.path], + })), + ); + +const invalidEvidence = ( + path: readonly (string | number)[], + field: string, + message: string, +): InvalidApplicationGraphEvidence => + new InvalidApplicationGraphEvidence([ + { path: [...path, field], reason: "invalid_value", message }, + ]); diff --git a/src/application/javascript/JavaScriptApplicationWorkflowService.ts b/src/application/javascript/JavaScriptApplicationWorkflowService.ts index a9c31ed12..f85330cee 100644 --- a/src/application/javascript/JavaScriptApplicationWorkflowService.ts +++ b/src/application/javascript/JavaScriptApplicationWorkflowService.ts @@ -17,6 +17,7 @@ import { err, ok, type Result } from "../../domain/result.js"; import { compareSourceToBundle } from "../../domain/javascript/sourceToBundleComparison.js"; import { compareSourceToBundleInputSchema } from "../../domain/javascript/sourceToBundleComparisonSchemas.js"; import { + applicationGraphEvidenceInputError, parseApplicationGraphEvidence, parseNativeApplicationEvidence, } from "./JavaScriptApplicationEvidenceGraph.js"; @@ -45,11 +46,24 @@ export const traceApplicationFeatureEvidenceValidated = ( input: z.output, ): Result => { const operation = "trace_application_feature"; - try { - const source = parseApplicationGraphEvidence(input.application); - const nativeEvidence = parseNativeApplicationEvidence( - input.native_observations, + const sourceResult = parseApplicationGraphEvidence(input.application, [ + "application", + ]); + if (!sourceResult.ok) + return err( + applicationGraphEvidenceInputError(operation, sourceResult.error), ); + const nativeResult = parseNativeApplicationEvidence( + input.native_observations, + ["native_observations"], + ); + if (!nativeResult.ok) + return err( + applicationGraphEvidenceInputError(operation, nativeResult.error), + ); + try { + const source = sourceResult.value; + const nativeEvidence = nativeResult.value; const result = traceApplicationFeature({ sourceEvidenceId: source.evidence.evidence_id, graph: source.graph, @@ -69,7 +83,7 @@ export const traceApplicationFeatureEvidenceValidated = ( ), ); } catch (cause: unknown) { - return workflowFailure(operation, cause, input); + return workflowFailure(operation, cause); } }; @@ -91,15 +105,35 @@ export const compareApplicationVersionsEvidenceValidated = ( input: z.output, ): Result => { const operation = "compare_application_versions"; + const leftResult = parseApplicationGraphEvidence(input.left, ["left"]); + if (!leftResult.ok) + return err(applicationGraphEvidenceInputError(operation, leftResult.error)); + const rightResult = parseApplicationGraphEvidence(input.right, ["right"]); + if (!rightResult.ok) + return err( + applicationGraphEvidenceInputError(operation, rightResult.error), + ); + const leftNativeResult = parseNativeApplicationEvidence( + input.left_native_observations, + ["left_native_observations"], + ); + if (!leftNativeResult.ok) + return err( + applicationGraphEvidenceInputError(operation, leftNativeResult.error), + ); + const rightNativeResult = parseNativeApplicationEvidence( + input.right_native_observations, + ["right_native_observations"], + ); + if (!rightNativeResult.ok) + return err( + applicationGraphEvidenceInputError(operation, rightNativeResult.error), + ); try { - const left = parseApplicationGraphEvidence(input.left); - const right = parseApplicationGraphEvidence(input.right); - const leftNative = parseNativeApplicationEvidence( - input.left_native_observations, - ); - const rightNative = parseNativeApplicationEvidence( - input.right_native_observations, - ); + const left = leftResult.value; + const right = rightResult.value; + const leftNative = leftNativeResult.value; + const rightNative = rightNativeResult.value; const result = compareJavaScriptApplicationVersions({ left: { evidenceId: left.evidence.evidence_id, @@ -128,7 +162,7 @@ export const compareApplicationVersionsEvidenceValidated = ( ), ); } catch (cause: unknown) { - return workflowFailure(operation, cause, input); + return workflowFailure(operation, cause); } }; @@ -137,8 +171,15 @@ export const compareSourceToBundleEvidenceValidated = ( input: z.output, ): Result => { const operation = "compare_source_to_bundle"; + const applicationResult = parseApplicationGraphEvidence(input.application, [ + "application", + ]); + if (!applicationResult.ok) + return err( + applicationGraphEvidenceInputError(operation, applicationResult.error), + ); try { - const application = parseApplicationGraphEvidence(input.application); + const application = applicationResult.value; const result = compareSourceToBundle({ reference: input.reference, application: { @@ -157,7 +198,7 @@ export const compareSourceToBundleEvidenceValidated = ( ), ); } catch (cause: unknown) { - return workflowFailure(operation, cause, input); + return workflowFailure(operation, cause); } }; @@ -182,9 +223,17 @@ export const compareJavaScriptExportShapesEvidenceValidated = ( input: z.output, ): Result => { const operation = "compare_javascript_export_shapes"; + const leftResult = parseApplicationGraphEvidence(input.left, ["left"]); + if (!leftResult.ok) + return err(applicationGraphEvidenceInputError(operation, leftResult.error)); + const rightResult = parseApplicationGraphEvidence(input.right, ["right"]); + if (!rightResult.ok) + return err( + applicationGraphEvidenceInputError(operation, rightResult.error), + ); try { - const left = parseApplicationGraphEvidence(input.left); - const right = parseApplicationGraphEvidence(input.right); + const left = leftResult.value; + const right = rightResult.value; const result = compareJavaScriptExportShapes({ left: { evidenceId: left.evidence.evidence_id, @@ -213,50 +262,17 @@ export const compareJavaScriptExportShapesEvidenceValidated = ( ), ); } catch (cause: unknown) { - return workflowFailure(operation, cause, input); + return workflowFailure(operation, cause); } }; const workflowFailure = ( operation: string, cause: unknown, - input: unknown, ): Result => - cause instanceof z.ZodError - ? err(analysisInputErrorFromIssues(operation, cause.issues, input)) - : cause instanceof TypeError && - SAFE_APPLICATION_INPUT_CONSTRAINTS.has(cause.message) - ? err( - new AnalysisInputError(operation, undefined, [ - { path: [], reason: "invalid_value", message: cause.message }, - ]), - ) - : err( - new AnalysisProtocolError( - "JavaScript application workflow produced an invalid result", - { cause }, - ), - ); - -const SAFE_APPLICATION_INPUT_CONSTRAINTS = new Set([ - "Evidence semantic identifier does not match its record", - "Application workflow requires authenticated analyze_javascript_application, reconcile_javascript_runtime, or project_managed_application_graph Evidence", - "JavaScript application Evidence authority or confidence is invalid", - "JavaScript application Evidence predicate does not match its result shape", - "JavaScript application Evidence subject does not match its result", - "Runtime reconciliation Evidence authority or confidence is invalid", - "Runtime reconciliation result references Evidence outside its envelope", - "Runtime reconciliation application layer is missing", - "Managed application graph Evidence authority or confidence is invalid", - "Managed application graph result references Evidence outside its envelope", - "Native handoff Evidence requires an artifact subject", - "Native handoff Evidence must be unique", - ...[ - "analyze_javascript_application", - "reconcile_javascript_runtime", - "project_managed_application_graph", - ].map( - (operation) => - `Evidence does not match the supported ${operation} contract`, - ), -]); + err( + new AnalysisProtocolError( + `JavaScript application workflow failed while producing ${operation}`, + { cause }, + ), + ); diff --git a/src/application/javascript/JavaScriptRuntimeReconciliationService.ts b/src/application/javascript/JavaScriptRuntimeReconciliationService.ts index bc4485552..d392ef182 100644 --- a/src/application/javascript/JavaScriptRuntimeReconciliationService.ts +++ b/src/application/javascript/JavaScriptRuntimeReconciliationService.ts @@ -85,7 +85,6 @@ const isPortableAbsolutePath = (path: string): boolean => /^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/u.test(path); const SAFE_RECONCILIATION_INPUT_CONSTRAINTS = new Set([ - "Evidence semantic identifier does not match its record", "JavaScript application Evidence subject disagrees with its result", "Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence", "Runtime Evidence target or declared role disagrees with its result", diff --git a/src/application/javascript/JavaScriptSemanticTraceService.ts b/src/application/javascript/JavaScriptSemanticTraceService.ts index 98dfb12c0..24413df43 100644 --- a/src/application/javascript/JavaScriptSemanticTraceService.ts +++ b/src/application/javascript/JavaScriptSemanticTraceService.ts @@ -5,6 +5,10 @@ import { AnalysisProtocolError, } from "../../domain/analysisErrorCore.js"; import { type AnalysisError } from "../../domain/analysisErrorBase.js"; +import { + applicationGraphEvidenceInputError, + parseApplicationGraphEvidence, +} from "./JavaScriptApplicationEvidenceGraph.js"; import type { Evidence } from "../../domain/evidence.js"; import { jsonValueSchema } from "../../domain/jsonValue.js"; import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js"; @@ -13,7 +17,6 @@ import { traceJavaScriptSemanticsInputSchema, } from "../../domain/javascript/javascriptSemanticTraceSchemas.js"; import { err, ok, type Result } from "../../domain/result.js"; -import { parseApplicationGraphEvidence } from "./JavaScriptApplicationEvidenceGraph.js"; import { createJavaScriptSemanticTraceEvidence } from "./JavaScriptApplicationWorkflowEvidence.js"; const OPERATION = "trace_javascript_semantics" as const; @@ -22,19 +25,26 @@ const OPERATION = "trace_javascript_semantics" as const; export const traceJavaScriptSemanticsEvidenceValidated = ( input: z.output, ): Result => { + const sourceResult = parseApplicationGraphEvidence(input.application, [ + "application", + ]); + if (!sourceResult.ok) + return err( + applicationGraphEvidenceInputError(OPERATION, sourceResult.error), + ); + const source = sourceResult.value; + if (source.semanticGraph === null) + return err( + new AnalysisInputError(OPERATION, undefined, [ + { + path: ["application"], + reason: "invalid_value", + expected: + "inline Evidence from analyze_javascript_application with a semantic graph", + }, + ]), + ); try { - const source = parseApplicationGraphEvidence(input.application); - if (source.semanticGraph === null) - return err( - new AnalysisInputError(OPERATION, undefined, [ - { - path: ["application"], - reason: "invalid_value", - expected: - "inline Evidence from analyze_javascript_application with a semantic graph", - }, - ]), - ); const query = queryJavaScriptSemanticGraph( source.semanticGraph, input.query, diff --git a/src/domain/evidence.ts b/src/domain/evidence.ts index 70d3e8c90..fe6c692a8 100644 --- a/src/domain/evidence.ts +++ b/src/domain/evidence.ts @@ -140,6 +140,18 @@ export const evidenceSchema = evidenceBaseSchema.superRefine( validateAnalysisProfileProvider, ); +const authenticatedEvidenceSchema = evidenceSchema.superRefine( + (evidence, context) => { + const { evidence_id: evidenceId, ...withoutId } = evidence; + if (computeEvidenceId(withoutId) !== evidenceId) + context.addIssue({ + code: "custom", + path: ["evidence_id"], + message: "Evidence semantic identifier does not match its record", + }); + }, +); + /** Complete observation whose normalized payload retains its operation-specific type. */ export type Evidence = z.infer< typeof evidenceSchema @@ -224,13 +236,7 @@ export const parseEvidence = (input: unknown): Evidence => { ? immutableEvidenceSnapshots.get(input) : undefined; if (immutable !== undefined) return immutable; - const evidence = evidenceSchema.parse(input); - const { evidence_id: evidenceId, ...withoutId } = evidence; - if (computeEvidenceId(withoutId) !== evidenceId) - throw new TypeError( - "Evidence semantic identifier does not match its record", - ); - return evidence; + return authenticatedEvidenceSchema.parse(input); }; /** Authenticate and seal a ledger-owned snapshot; external mutable values are copied first. */ diff --git a/src/domain/evidenceBundle.ts b/src/domain/evidenceBundle.ts index c914ab319..39dcf43e7 100644 --- a/src/domain/evidenceBundle.ts +++ b/src/domain/evidenceBundle.ts @@ -243,7 +243,20 @@ export const parseEvidenceBundle = (input: unknown): EvidenceBundle => { throw new TypeError("Evidence bundle contains duplicate record IDs"); validateUnknownGraph(parsed.unknowns, parsed.records); const canonical = createEvidenceBundle( - parsed.records.map(parseEvidence), + parsed.records.map((record, index) => { + try { + return parseEvidence(record); + } catch (cause: unknown) { + if (cause instanceof z.ZodError) + throw new z.ZodError( + cause.issues.map((issue) => ({ + ...issue, + path: ["records", index, ...issue.path], + })), + ); + throw cause; + } + }), parsed.unknowns, ); if (JSON.stringify(parsed) !== JSON.stringify(canonical)) diff --git a/tests/boundary/filesystem/evidenceBundleFiles.test.ts b/tests/boundary/filesystem/evidenceBundleFiles.test.ts index 11216b671..d5a92938a 100644 --- a/tests/boundary/filesystem/evidenceBundleFiles.test.ts +++ b/tests/boundary/filesystem/evidenceBundleFiles.test.ts @@ -313,7 +313,7 @@ describe("evidence bundle filesystem adapter", () => { error: { _tag: "EvidenceIntegrityError", userMessage: expect.stringContaining( - "Evidence semantic identifier does not match its record", + "at records.0.evidence_id: Evidence semantic identifier does not match its record", ), }, }); diff --git a/tests/boundary/filesystem/javascriptApplicationWorkflows.test.ts b/tests/boundary/filesystem/javascriptApplicationWorkflows.test.ts index 5276b510a..8da2a46a5 100644 --- a/tests/boundary/filesystem/javascriptApplicationWorkflows.test.ts +++ b/tests/boundary/filesystem/javascriptApplicationWorkflows.test.ts @@ -320,7 +320,7 @@ describe("complete comparison projections", () => { }); describe("JavaScript application workflow error diagnostics", () => { - it("returns safe explicit Evidence constraints from graph workflows", async () => { + it("identifies the inconsistent Evidence subject in graph workflows", async () => { const root = await createTestTempDirectory( "rea-application-workflow-diagnostics-", ); @@ -328,10 +328,10 @@ describe("JavaScript application workflow error diagnostics", () => { const evidence = await analyzeFixture(root); const subject = evidence.subject; if (subject === null) throw new Error("Analysis Evidence subject missing"); - const secretPath = "/private/token=do-not-return"; + const inconsistentPath = "/different/application.js"; const inconsistent = { ...evidence, - subject: { ...subject, local_path: secretPath }, + subject: { ...subject, local_path: inconsistentPath }, }; const result = traceApplicationFeatureEvidence({ @@ -346,11 +346,10 @@ describe("JavaScript application workflow error diagnostics", () => { expect(result.error.issues).toContainEqual( expect.objectContaining({ reason: "invalid_value", - message: - "JavaScript application Evidence subject does not match its result", + path: ["application", "subject"], + message: expect.stringContaining("subject must match"), }), ); - expect(JSON.stringify(result.error.issues)).not.toContain(secretPath); }); it("preserves schema-authored Evidence validation messages", async () => { diff --git a/tests/boundary/filesystem/javascriptExportContainerCoverage.test.ts b/tests/boundary/filesystem/javascriptExportContainerCoverage.test.ts index f410e4f29..bea6adbac 100644 --- a/tests/boundary/filesystem/javascriptExportContainerCoverage.test.ts +++ b/tests/boundary/filesystem/javascriptExportContainerCoverage.test.ts @@ -232,7 +232,9 @@ const analyzeReturn = async (root: string, properties: string) => { await writeFixtureFiles(root, { "parser.mjs": `${prefix}${expression});\n` }); const analyzed = await analyzeJavaScriptApplication({ input_path: root }); if (!analyzed.ok) throw analyzed.error; - const source = parseApplicationGraphEvidence(analyzed.value); + const parsed = parseApplicationGraphEvidence(analyzed.value); + if (!parsed.ok) throw new Error("Analysis Evidence must parse"); + const source = parsed.value; const observation = source.graph.nodes .flatMap(({ observations }) => observations) .find( diff --git a/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts b/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts index 5be94b62d..0039be5c1 100644 --- a/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts +++ b/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts @@ -938,7 +938,9 @@ const analyzeGraph = async (root: string) => { input_path: root, }); if (!result.ok) throw result.error; - return parseApplicationGraphEvidence(result.value); + const parsed = parseApplicationGraphEvidence(result.value); + if (!parsed.ok) throw new Error("Analysis Evidence must parse"); + return parsed.value; }; const analyzeSources = async ( diff --git a/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts b/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts index eccc05883..77d383cbe 100644 --- a/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts +++ b/tests/boundary/filesystem/javascriptRequireLiteralPaths.test.ts @@ -15,7 +15,9 @@ const analyze = async (root: string) => { format: "directory", }); if (!result.ok) throw result.error; - const authenticated = parseApplicationGraphEvidence(result.value); + const parsed = parseApplicationGraphEvidence(result.value); + if (!parsed.ok) throw new Error("Analysis Evidence must parse"); + const authenticated = parsed.value; return { graph: authenticated.graph, result: javascriptApplicationAnalysisResultSchema.parse( diff --git a/tests/boundary/filesystem/sourceToBundlePaths.test.ts b/tests/boundary/filesystem/sourceToBundlePaths.test.ts index 3514e5ead..7dcd910ff 100644 --- a/tests/boundary/filesystem/sourceToBundlePaths.test.ts +++ b/tests/boundary/filesystem/sourceToBundlePaths.test.ts @@ -668,9 +668,16 @@ it("rejects static application Evidence whose subject path disagrees with its re }, }; - expect(() => parseApplicationGraphEvidence(inconsistent)).toThrow( - "JavaScript application Evidence subject does not match its result", - ); + const parsed = parseApplicationGraphEvidence(inconsistent); + expect(parsed.ok).toBe(false); + if (!parsed.ok) + expect(parsed.error.issues).toContainEqual( + expect.objectContaining({ + path: ["subject"], + reason: "invalid_value", + message: expect.stringContaining("subject must match"), + }), + ); }); const compareTrees = async (previous: string, current: string) => { @@ -682,9 +689,11 @@ const compareTrees = async (previous: string, current: string) => { if (!reference.ok) throw new Error(reference.error.message); const analyzed = await analyzeJavaScriptApplication({ input_path: current }); if (!analyzed.ok) throw analyzed.error; - const application = parseApplicationGraphEvidence( + const parsedApplication = parseApplicationGraphEvidence( JSON.parse(JSON.stringify(analyzed.value)), ); + if (!parsedApplication.ok) throw new Error("Analysis Evidence must parse"); + const application = parsedApplication.value; const comparison = compareSourceToBundle({ reference: reference.value, application: { diff --git a/tests/boundary/javascriptSemanticTraceEvidence.test.ts b/tests/boundary/javascriptSemanticTraceEvidence.test.ts new file mode 100644 index 000000000..def3bde04 --- /dev/null +++ b/tests/boundary/javascriptSemanticTraceEvidence.test.ts @@ -0,0 +1,221 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect, it } from "vitest"; +import { Ajv2020 } from "ajv/dist/2020.js"; + +import { createApplicationMcpHarness } from "../fixtures/applicationMcpHarness.js"; +import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { createCli } from "../../src/cli.js"; +import { createEvidence, parseEvidence } from "../../src/domain/evidence.js"; +import type { JsonValue } from "../../src/domain/jsonValue.js"; +import { analysisCliErrorEnvelopeSchema } from "../../src/contracts/errorSchemas.js"; +import { toolContract } from "../../src/contracts/toolContracts.js"; +import { javaScriptSemanticTraceResultSchema } from "../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; +import { resolveJavaScriptSemanticEvidence } from "../../src/domain/javascript/javascriptSemanticGraph.js"; + +const SEMANTIC_GRAPH_ID = `jsrg_${"0".repeat(64)}`; + +it("reports invalid nested semantic graph Evidence as caller input through CLI and SDK MCP", async () => { + const root = await createTestTempDirectory("rea-semantic-trace-input-"); + await mkdir(join(root, "src")); + await writeFile( + join(root, "src", "main.js"), + "export function parse(value) { return JSON.parse(value); }\n", + ); + + const cli = createCli({}); + const analyzed = await serveCli(cli, [ + "analyze-javascript-application", + root, + "--json", + ]); + expect(analyzed.exitCode).toBe(0); + const sourceEvidence = parseEvidence(JSON.parse(analyzed.stdout)); + const normalizedResult = structuredClone(sourceEvidence.normalized_result); + if (!isJsonObject(normalizedResult)) + throw new Error("CLI analysis result must be an object"); + const semanticGraph = normalizedResult.semantic_graph; + if (!isJsonObject(semanticGraph)) + throw new Error("CLI analysis must include a semantic graph"); + const firstNode = semanticGraph.nodes; + if (!Array.isArray(firstNode) || !isJsonObject(firstNode[0])) + throw new Error("CLI semantic graph must include a node"); + const seedNodeId = firstNode[0].node_id; + if (typeof seedNodeId !== "string") + throw new Error("CLI semantic graph node must have an identifier"); + semanticGraph.graph_id = SEMANTIC_GRAPH_ID; + + const subject = sourceEvidence.subject; + if (subject === null) throw new Error("CLI Evidence must include a subject"); + const malformedEvidence = createEvidence( + { + path: subject.local_path, + sha256: subject.digest.sha256, + format: subject.format, + ...(subject.architecture === null + ? {} + : { architecture: subject.architecture }), + }, + sourceEvidence.provider, + { + predicateType: sourceEvidence.predicate_type, + operation: sourceEvidence.operation, + parameters: sourceEvidence.parameters, + result: normalizedResult, + confidence: sourceEvidence.confidence, + authority: sourceEvidence.authority, + }, + ); + expect(malformedEvidence.evidence_id).not.toBe(sourceEvidence.evidence_id); + + const arguments_ = { + application: malformedEvidence, + query: { + seed: { kind: "semantic-node", node_id: seedNodeId }, + direction: "backward-provenance", + }, + }; + const cliTrace = await serveCli(cli, [ + "trace-javascript-semantics", + JSON.stringify(arguments_), + "--json", + ]); + const cliEnvelope = analysisCliErrorEnvelopeSchema.parse( + JSON.parse(cliTrace.stdout), + ); + const { error: _label, ...cliError } = cliEnvelope; + expect(cliError).toMatchObject({ + code: "invalid_request", + category: "invalid_input", + details: { + issues: [ + { + path: [ + "application", + "normalized_result", + "semantic_graph", + "graph_id", + ], + reason: "invalid_value", + }, + ], + }, + }); + + const harness = await createApplicationMcpHarness(); + try { + await assertSuccessfulTraceParity( + cli, + harness, + sourceEvidence, + arguments_.query, + ); + + const mcpTrace = await harness.client.callTool({ + name: "trace_javascript_semantics", + arguments: arguments_, + }); + const { error: mcpError } = parseMcpToolError(mcpTrace); + expect(mcpError).toEqual(cliError); + } finally { + await harness.close(); + } +}); + +const assertSuccessfulTraceParity = async ( + cli: ReturnType, + harness: Awaited>, + application: ReturnType, + query: { readonly seed: unknown; readonly direction: string }, +): Promise => { + const arguments_ = { application, query }; + const cliResponse = await serveCli(cli, [ + "trace-javascript-semantics", + JSON.stringify(arguments_), + "--json", + ]); + const cliEvidence = parseEvidence(JSON.parse(cliResponse.stdout)); + const cliResult = javaScriptSemanticTraceResultSchema.parse( + cliEvidence.normalized_result, + ); + assertTraceContextsResolve(cliResult); + + const mcpResponse = await harness.client.callTool({ + name: "trace_javascript_semantics", + arguments: arguments_, + }); + expect(mcpResponse.isError).not.toBe(true); + const { tools } = await harness.client.listTools(); + const advertised = tools.find( + ({ name }) => name === "trace_javascript_semantics", + ); + if (advertised?.outputSchema === undefined) + throw new Error("Semantic trace SDK output schema is missing"); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + const outputSchema: Record = advertised.outputSchema; + expect(ajv.validateSchema(outputSchema)).toBe(true); + expect(ajv.validate(outputSchema, mcpResponse.structuredContent)).toBe(true); + const mcpEvidence = toolContract( + "trace_javascript_semantics", + ).outputSchema.parse(mcpResponse.structuredContent); + expect(mcpEvidence.normalized_result).toEqual(cliResult); + expect(mcpEvidence).toEqual(cliEvidence); +}; + +const assertTraceContextsResolve = ( + result: ReturnType, +): void => { + const contexts = new Map( + result.evidence_contexts.map((context) => [context.context_id, context]), + ); + const references = [ + ...result.nodes.map(({ evidence }) => evidence), + ...result.relations.map(({ evidence }) => evidence), + ...result.unknowns.map(({ evidence }) => evidence), + ]; + const referencedIds = new Set(); + for (const reference of references) { + const context = contexts.get(reference.context_id); + expect(context, reference.context_id).toBeDefined(); + if (context === undefined) continue; + referencedIds.add(reference.context_id); + expect( + resolveJavaScriptSemanticEvidence( + { evidence_contexts: result.evidence_contexts }, + reference, + ), + ).toMatchObject({ + ...Object.fromEntries( + Object.entries(context).filter(([key]) => key !== "context_id"), + ), + location: reference.location, + }); + } + expect([...referencedIds].toSorted()).toEqual( + [...contexts.keys()].toSorted(), + ); + expect(contexts.size).toBeGreaterThan(0); +}; + +const serveCli = async ( + cli: ReturnType, + arguments_: readonly string[], +): Promise<{ readonly stdout: string; readonly exitCode: number }> => { + let stdout = ""; + let exitCode = 0; + await cli.serve([...arguments_], { + env: {}, + exit: (code) => { + exitCode = code; + }, + stdout: (text) => { + stdout += text; + }, + }); + return { stdout, exitCode }; +}; + +const isJsonObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts index 7667b1ffb..f1aadf973 100644 --- a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts @@ -175,7 +175,7 @@ it("names the side and constraint when Evidence is not a usable capture", async error: { code: "evidence_integrity_mismatch", message: expect.stringContaining( - "The right Evidence failed validation (Evidence semantic identifier does not match its record)", + "The right Evidence failed validation (at evidence_id: Evidence semantic identifier does not match its record)", ), }, }); From f62b44971deee0e99df6fcf32758c8e5592400ed Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:15:54 +0800 Subject: [PATCH 073/189] fix(mcp): advertise primitive semantic literal seeds --- .../javascriptSemanticQuerySchemas.ts | 18 ++++-------- .../retainedApplicationEvidenceMcp.test.ts | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticQuerySchemas.ts b/src/domain/javascript/javascriptSemanticQuerySchemas.ts index d9c93446a..a88adc706 100644 --- a/src/domain/javascript/javascriptSemanticQuerySchemas.ts +++ b/src/domain/javascript/javascriptSemanticQuerySchemas.ts @@ -8,22 +8,16 @@ import { javaScriptSemanticEvidenceContextSchema, javaScriptSemanticUnknownSchema, } from "./javascriptSemanticGraphSchemas.js"; -import { jsonValueSchema } from "../jsonValue.js"; import { digestSchema } from "../digests.js"; import { prefixedDigestSchema } from "../digests.js"; const semanticNodeIdSchema = prefixedDigestSchema("jsrg_node"); -const literalValueSchema = jsonValueSchema.refine( - (value) => - value === null || - typeof value === "string" || - typeof value === "number" || - typeof value === "boolean", - "Literal seeds accept only JSON primitive values", -); -// Zod derivations drop the shared schema's JSON Schema projection override; -// re-apply it so MCP catalog generation keeps projecting `{}`. -literalValueSchema._zod.toJSONSchema = () => ({}); +const literalValueSchema = z.union([ + z.string(), + z.number(), + z.boolean(), + z.null(), +]); const literalSeedSchema = z.strictObject({ kind: z.literal("literal"), diff --git a/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts b/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts index ef90cd7e4..ebc7062a9 100644 --- a/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts +++ b/tests/boundary/mcp/retainedApplicationEvidenceMcp.test.ts @@ -37,6 +37,34 @@ async function connect() { return { client, session }; } +it("advertises the primitive literal seeds accepted by semantic tracing", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + const tool = tools.find(({ name }) => name === "trace_javascript_semantics"); + if (tool === undefined) throw new Error("Semantic trace tool is missing"); + const validate = new Ajv2020({ + strict: false, + validateFormats: false, + }).compile(tool.inputSchema); + for (const value of ["literal", 42, true, null, {}, []]) { + const primitive = value === null || typeof value !== "object"; + const arguments_ = { + application, + query: { + seed: { kind: "literal", value }, + direction: "backward-provenance", + }, + }; + expect(validate(arguments_), JSON.stringify(value)).toBe(primitive); + const result = await client.callTool({ + name: tool.name, + arguments: arguments_, + }); + if (primitive) expect(result.isError).not.toBe(true); + else expect(result.isError).toBe(true); + } +}); + it("runs the same trace/compare workflows with inline and retained application Evidence", async () => { const { client, session } = await connect(); expect(session.recordEvidence(pair.left).ok).toBe(true); From 415145d04f09a15cbfb7dda8ea9dc363a77f9bf0 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:16:08 +0800 Subject: [PATCH 074/189] fix(process)!: retain per-file digest open failures BREAKING CHANGE: Filesystem digest omission entries now require system_code; budget and changed-file omissions use null, and unavailable-file omissions preserve the operating-system error code. --- docs/process-capture.md | 6 +- src/domain/process/processCaptureCoverage.ts | 7 +- .../process/processCaptureValidation.ts | 5 +- .../capture/FilesystemCoverage.test.ts | 47 ++++++- .../capture/FilesystemSnapshot.test.ts | 37 +++++- src/process/capture/FilesystemSnapshot.ts | 122 ++++++++++++++---- .../process/processTruncationAdapters.test.ts | 2 + .../fixtures/filesystemSnapshotFifoProbe.mjs | 11 +- 8 files changed, 202 insertions(+), 35 deletions(-) diff --git a/docs/process-capture.md b/docs/process-capture.md index b000994c0..316d36c99 100644 --- a/docs/process-capture.md +++ b/docs/process-capture.md @@ -143,8 +143,10 @@ Every capture requires `truncation_details`, with separate accounting for: - `filesystem_before` and `filesystem_after`: file-count/depth limits, enumeration failures, whole-file hash budget and bytes successfully hashed. Each retained regular file without a digest has an aliased path, size, - remaining budget and reason: `file_bytes_budget` or - `file_changed_or_short_read`. A file too large for the remaining budget is + remaining budget and reason: `file_bytes_budget`, + `file_changed_or_short_read`, or `file_unavailable`. Its `system_code` is + null unless an OS file operation failed, in which case it preserves the + reported error code. A file too large for the remaining budget is skipped; a later smaller file can still be hashed. Hash omissions do not imply incomplete path enumeration. - `process`: sampling limit and whether sampling ended partially. Coverage diff --git a/src/domain/process/processCaptureCoverage.ts b/src/domain/process/processCaptureCoverage.ts index a93972912..72bbb9fb1 100644 --- a/src/domain/process/processCaptureCoverage.ts +++ b/src/domain/process/processCaptureCoverage.ts @@ -25,7 +25,12 @@ export const filesystemCoverageSchema = z.strictObject({ path: z.string(), size_bytes: z.number().int().nonnegative(), remaining_budget_bytes: z.number().int().nonnegative(), - reason: z.enum(["file_bytes_budget", "file_changed_or_short_read"]), + reason: z.enum([ + "file_bytes_budget", + "file_changed_or_short_read", + "file_unavailable", + ]), + system_code: z.string().nullable(), }), ), }); diff --git a/src/domain/process/processCaptureValidation.ts b/src/domain/process/processCaptureValidation.ts index fe5479689..a14cd129b 100644 --- a/src/domain/process/processCaptureValidation.ts +++ b/src/domain/process/processCaptureValidation.ts @@ -200,7 +200,10 @@ const validateCoverage = ( coverage.hash_omissions.every( (omission) => unhashedFiles.get(omission.path)?.size === omission.size_bytes && - omission.remaining_budget_bytes <= coverage.hash_budget_bytes, + omission.remaining_budget_bytes <= coverage.hash_budget_bytes && + (omission.reason === "file_unavailable" + ? omission.system_code !== null + : omission.system_code === null), ), `truncation_details.${name}.hash_omissions`, "every retained regular file without a digest must have one matching omission reason"); require(coverage.hashed_bytes === files diff --git a/src/process/capture/FilesystemCoverage.test.ts b/src/process/capture/FilesystemCoverage.test.ts index ee8de9fac..36ebfc6de 100644 --- a/src/process/capture/FilesystemCoverage.test.ts +++ b/src/process/capture/FilesystemCoverage.test.ts @@ -1,4 +1,4 @@ -import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { parseProcessScenario } from "../../domain/process/processScenario.js"; @@ -81,6 +81,51 @@ it("distinguishes unavailable content hashes from completed path enumeration", a ).toMatchObject({ status: "deleted", before: { sha256: null }, after: null }); }); +it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "retains unreadable-file and sibling observations in a complete snapshot", + async () => { + const root = await createTestTempDirectory("rea-fs-unreadable-file-"); + const unreadable = join(root, "unreadable.txt"); + const readable = join(root, "readable.txt"); + await writeFile(unreadable, "permission denied"); + await writeFile(readable, "still observed"); + await chmod(unreadable, 0); + const scenario = parseProcessScenario({ + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [root], + }); + + try { + const snapshot = await snapshotRoots(scenario); + expect(snapshot.files.map(({ path }) => path)).toEqual([ + "root_0:.", + "root_0:readable.txt", + "root_0:unreadable.txt", + ]); + expect( + snapshot.files.find(({ path }) => path === "root_0:readable.txt") + ?.sha256, + ).not.toBeNull(); + expect( + snapshot.files.find(({ path }) => path === "root_0:unreadable.txt"), + ).toMatchObject({ type: "file", size: 17, sha256: null }); + expect(snapshot.coverage.hash_omissions).toContainEqual({ + path: "root_0:unreadable.txt", + size_bytes: 17, + remaining_budget_bytes: + scenario.limits.file_bytes - Buffer.byteLength("still observed"), + reason: "file_unavailable", + system_code: "EACCES", + }); + expect(snapshot.completeRoots).toEqual(["root_0"]); + } finally { + await chmod(unreadable, 0o600); + await rm(root, { recursive: true, force: true }); + } + }, +); + it("preserves creation when the selected root was observed missing before capture", async () => { const root = await createTestTempDirectory("rea-fs-missing-root-"); const file = join(root, "created.txt"); diff --git a/src/process/capture/FilesystemSnapshot.test.ts b/src/process/capture/FilesystemSnapshot.test.ts index b7e141018..16799b973 100644 --- a/src/process/capture/FilesystemSnapshot.test.ts +++ b/src/process/capture/FilesystemSnapshot.test.ts @@ -44,7 +44,11 @@ it("does not hash a replacement file using the earlier path metadata", async () await rm(path); await writeFile(path, "replacement with a different identity and size\n"); - await expect(hashFile(path, expected, 1_000)).resolves.toBeNull(); + await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }); } finally { await rm(directory, { recursive: true, force: true }); } @@ -76,7 +80,29 @@ it("rejects a same-size rewrite even when its modification time is restored", as }); expect(rewritten.ctimeMs).not.toBe(expected.ctimeMs); - await expect(hashFile(path, expected, 1_000)).resolves.toBeNull(); + await expect(hashFile(path, expected, 1_000)).resolves.toMatchObject({ + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +it("reports a file removed between metadata observation and open", async () => { + const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-open-race-")); + const path = join(directory, "observed-file"); + try { + await writeFile(path, "captured file\n"); + const expected = await lstat(path); + await rm(path); + + await expect(hashFile(path, expected, 1_000)).resolves.toEqual({ + state: "omitted", + reason: "file_unavailable", + system_code: "ENOENT", + }); } finally { await rm(directory, { recursive: true, force: true }); } @@ -116,9 +142,12 @@ it.skipIf(process.platform === "win32")( // hashFile reaches `open` synchronously before its first suspension, so // this abort is observed after the descriptor is acquired and is handled // by the `finally` close path. - controller.abort(); + const reason = Object.assign(new Error("cancelled while opening"), { + code: "EACCES", + }); + controller.abort(reason); - await expect(hashing).rejects.toMatchObject({ name: "AbortError" }); + await expect(hashing).rejects.toBe(reason); expect(await countOpenDescriptorsFor(path)).toBe(0); } finally { await rm(directory, { recursive: true, force: true }); diff --git a/src/process/capture/FilesystemSnapshot.ts b/src/process/capture/FilesystemSnapshot.ts index 281151afc..17dd91174 100644 --- a/src/process/capture/FilesystemSnapshot.ts +++ b/src/process/capture/FilesystemSnapshot.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import { constants as fsConstants } from "node:fs"; import { lstat, open, readdir, readlink } from "node:fs/promises"; import { dirname, join, relative, resolve } from "node:path"; +import type { FileHandle } from "node:fs/promises"; import type { ProcessScenario } from "../../domain/process/processScenario.js"; import type { FilesystemCoverage } from "../../domain/process/processCaptureCoverage.js"; import type { Stats } from "node:fs"; @@ -29,6 +30,23 @@ const hasSameFileState = (before: Stats, after: Stats): boolean => before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs; +const fileUnavailableSystemCode = (cause: unknown): string | undefined => { + if (!(cause instanceof Error) || !("code" in cause)) return undefined; + const code = cause.code; + return typeof code === "string" && + [ + "EACCES", + "EISDIR", + "ELOOP", + "ENOTDIR", + "ENOENT", + "EPERM", + "ESTALE", + ].includes(code) + ? code + : undefined; +}; + const lstatIfPresent = async (path: string): Promise => { try { return await lstat(path); @@ -39,26 +57,51 @@ const lstatIfPresent = async (path: string): Promise => { } }; +/** Reports a complete digest or an explicit per-file reason hashing was omitted. */ +export type FileHashOutcome = + | { readonly state: "hashed"; readonly sha256: string } + | { + readonly state: "omitted"; + readonly reason: "file_changed_or_short_read" | "file_unavailable"; + readonly system_code: string | null; + }; + /** Hash a file only when its opened descriptor still matches the captured path state. */ export const hashFile = async ( path: string, expected: Stats, maxBytes: number, signal?: AbortSignal, -): Promise => { +): Promise => { signal?.throwIfAborted(); - const handle = await open( - path, - fsConstants.O_RDONLY | - (fsConstants.O_NOFOLLOW ?? 0) | - (fsConstants.O_NONBLOCK ?? 0), - ); + let handle: FileHandle; + try { + handle = await open( + path, + fsConstants.O_RDONLY | + (fsConstants.O_NOFOLLOW ?? 0) | + (fsConstants.O_NONBLOCK ?? 0), + ); + } catch (cause: unknown) { + signal?.throwIfAborted(); + const systemCode = fileUnavailableSystemCode(cause); + if (systemCode === undefined) throw cause; + return { + state: "omitted", + reason: "file_unavailable", + system_code: systemCode, + }; + } try { signal?.throwIfAborted(); const stats = await handle.stat(); signal?.throwIfAborted(); if (!hasSameFileState(expected, stats) || stats.size > maxBytes) - return null; + return { + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }; const hash = createHash("sha256"); const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes)); let position = 0; @@ -70,14 +113,33 @@ export const hashFile = async ( Math.min(buffer.length, stats.size - position), position, ); - if (bytesRead === 0) return null; + if (bytesRead === 0) + return { + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }; hash.update(buffer.subarray(0, bytesRead)); position += bytesRead; } const after = await handle.stat(); signal?.throwIfAborted(); - if (!hasSameFileState(stats, after)) return null; - return hash.digest("hex"); + if (!hasSameFileState(stats, after)) + return { + state: "omitted", + reason: "file_changed_or_short_read", + system_code: null, + }; + return { state: "hashed", sha256: hash.digest("hex") }; + } catch (cause: unknown) { + signal?.throwIfAborted(); + const systemCode = fileUnavailableSystemCode(cause); + if (systemCode === undefined) throw cause; + return { + state: "omitted", + reason: "file_unavailable", + system_code: systemCode, + }; } finally { await handle.close(); } @@ -136,22 +198,34 @@ export const snapshotRoots = async ( return true; } if (stats.isFile()) { - const sha256 = - remainingBytes >= stats.size - ? await hashFile(path, stats, remainingBytes, signal) - : null; - remainingBytes -= sha256 === null ? 0 : stats.size; - if (sha256 === null) { - truncated = true; - hashOmissions.push({ + let sha256: string | null = null; + let omission: FilesystemCoverage["hash_omissions"][number] | undefined; + if (remainingBytes < stats.size) { + omission = { path: `${rootAlias}:${relativePath}`, size_bytes: stats.size, remaining_budget_bytes: remainingBytes, - reason: - remainingBytes < stats.size - ? "file_bytes_budget" - : "file_changed_or_short_read", - }); + reason: "file_bytes_budget", + system_code: null, + }; + } else { + const outcome = await hashFile(path, stats, remainingBytes, signal); + if (outcome.state === "hashed") { + sha256 = outcome.sha256; + remainingBytes -= stats.size; + } else { + omission = { + path: `${rootAlias}:${relativePath}`, + size_bytes: stats.size, + remaining_budget_bytes: remainingBytes, + reason: outcome.reason, + system_code: outcome.system_code, + }; + } + } + if (omission !== undefined) { + truncated = true; + hashOmissions.push(omission); } entries.push({ path: `${rootAlias}:${relativePath}`, diff --git a/tests/boundary/process/processTruncationAdapters.test.ts b/tests/boundary/process/processTruncationAdapters.test.ts index 34c1ccb3a..20d41e639 100644 --- a/tests/boundary/process/processTruncationAdapters.test.ts +++ b/tests/boundary/process/processTruncationAdapters.test.ts @@ -187,6 +187,7 @@ itWithCaptureCapability.each(["cli", "mcp"] as const)( size_bytes: 8, remaining_budget_bytes: 1, reason: "file_bytes_budget", + system_code: null, }, ], }); @@ -229,6 +230,7 @@ itWithCaptureCapability.each(["cli", "mcp"] as const)( path: "root_0:b.txt", reason: "file_bytes_budget", remaining_budget_bytes: 1, + system_code: null, }, ], }); diff --git a/tests/fixtures/filesystemSnapshotFifoProbe.mjs b/tests/fixtures/filesystemSnapshotFifoProbe.mjs index de3e466b3..984d6e9f7 100644 --- a/tests/fixtures/filesystemSnapshotFifoProbe.mjs +++ b/tests/fixtures/filesystemSnapshotFifoProbe.mjs @@ -18,6 +18,13 @@ execFileSync("mkfifo", [path]); // This invokes the production lstat-to-open hashing seam with a known captured // regular-file identity. The owner test bounds this child so an O_RDONLY FIFO // regression cannot hang Vitest. -const digest = await hashFile(path, expected, 1_000); -if (digest !== null) throw new Error("Expected the FIFO to be rejected"); +const outcome = await hashFile(path, expected, 1_000); +if ( + outcome.state !== "omitted" || + outcome.reason !== "file_changed_or_short_read" || + outcome.system_code !== null +) + throw new Error( + `Expected the FIFO to be omitted as a changed file: ${JSON.stringify(outcome)}`, + ); process.stdout.write("rejected\n"); From 006b295f1de19fd5351832cf52d98a202a5cd5cd Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:30:58 +0800 Subject: [PATCH 075/189] refactor(javascript): parse runtime evidence into one verified owner --- .../JavaScriptRuntimeReconciliationService.ts | 59 +-- .../javascriptApplicationWorkflowExamples.ts | 12 +- .../javascriptRuntimeReconciliation.ts | 32 +- .../javascriptRuntimeReconciliationActive.ts | 36 +- ...riptRuntimeReconciliationCaptureParsing.ts | 481 ++++++++++++++++++ .../javascriptRuntimeReconciliationGraph.ts | 6 +- ...iptRuntimeReconciliationInputValidation.ts | 57 +++ .../javascriptRuntimeReconciliationParsing.ts | 465 ++--------------- .../javascriptRuntimeReconciliationResult.ts | 6 +- .../javascriptRuntimeReconciliationRuntime.ts | 2 +- .../browser/cdpScriptMetadata.test.ts | 2 +- .../javascriptRuntimeObservation.test.ts | 94 ++++ .../javascriptRuntimeUnresolvedTarget.test.ts | 15 +- ...riptRuntimeReconciliationAmbiguity.test.ts | 21 +- .../javascriptRuntimeReconciliation.test.ts | 63 ++- 15 files changed, 839 insertions(+), 512 deletions(-) create mode 100644 src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.ts create mode 100644 src/domain/javascript/javascriptRuntimeReconciliationInputValidation.ts diff --git a/src/application/javascript/JavaScriptRuntimeReconciliationService.ts b/src/application/javascript/JavaScriptRuntimeReconciliationService.ts index d392ef182..ca96d81bc 100644 --- a/src/application/javascript/JavaScriptRuntimeReconciliationService.ts +++ b/src/application/javascript/JavaScriptRuntimeReconciliationService.ts @@ -1,14 +1,15 @@ import { resolve } from "node:path"; import { z } from "zod"; -import { - AnalysisInputError, - AnalysisProtocolError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisProtocolError } from "../../domain/analysisErrorCore.js"; import { type AnalysisError } from "../../domain/analysisErrorBase.js"; import type { Evidence } from "../../domain/evidence.js"; import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; -import { reconcileJavaScriptRuntime } from "../../domain/javascript/javascriptRuntimeReconciliation.js"; +import { + parseRuntimeReconciliationInput, + reconcileJavaScriptRuntime, + type ParsedRuntimeReconciliationInput, +} from "../../domain/javascript/javascriptRuntimeReconciliation.js"; import { reconcileJavaScriptRuntimeInputSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { err, ok, type Result } from "../../domain/result.js"; import { createJavaScriptRuntimeReconciliationEvidence } from "./JavaScriptRuntimeReconciliationEvidence.js"; @@ -31,26 +32,30 @@ export const reconcileJavaScriptRuntimeEvidence = ( export const reconcileJavaScriptRuntimeEvidenceValidated = ( parsedInput: z.output, ): Result => { + let parsed: ParsedRuntimeReconciliationInput; try { - const input = reconcileJavaScriptRuntimeInputSchema.parse( + parsed = parseRuntimeReconciliationInput( normalizeRuntimeMappingRoots(parsedInput), ); - const result = reconcileJavaScriptRuntime(input); - return ok(createJavaScriptRuntimeReconciliationEvidence(input, result)); } catch (cause: unknown) { if (cause instanceof z.ZodError) return err( analysisInputErrorFromIssues(OPERATION, cause.issues, parsedInput), ); - if ( - cause instanceof TypeError && - SAFE_RECONCILIATION_INPUT_CONSTRAINTS.has(cause.message) - ) - return err( - new AnalysisInputError(OPERATION, undefined, [ - { path: [], reason: "invalid_value", message: cause.message }, - ]), - ); + return err( + new AnalysisProtocolError( + "JavaScript runtime reconciliation input parsing failed", + { cause }, + ), + ); + } + + try { + const result = reconcileJavaScriptRuntime(parsed); + return ok( + createJavaScriptRuntimeReconciliationEvidence(parsed.input, result), + ); + } catch (cause: unknown) { return err( new AnalysisProtocolError( "JavaScript runtime reconciliation produced an invalid result", @@ -83,23 +88,3 @@ const isPortableAbsolutePath = (path: string): boolean => path.startsWith("/") || /^[a-z]:[\\/]/iu.test(path) || /^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/u.test(path); - -const SAFE_RECONCILIATION_INPUT_CONSTRAINTS = new Set([ - "JavaScript application Evidence subject disagrees with its result", - "Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence", - "Runtime Evidence target or declared role disagrees with its result", - "Runtime Evidence contains an invalid builtin location", - "Runtime Evidence target disagrees with its captured result", - "Browser Evidence target is outside its recorded origin scope", - "Runtime Evidence contains source without source-capture selection", - "Active Electron Evidence application path disagrees with its configured root", - ...[ - "inspect_web_page", - "inspect_electron_page", - "observe_javascript_runtime", - "capture_electron_scenario", - ].map( - (operation) => - `Evidence does not match the supported ${operation} contract`, - ), -]); diff --git a/src/contracts/javascript/javascriptApplicationWorkflowExamples.ts b/src/contracts/javascript/javascriptApplicationWorkflowExamples.ts index 7e9b6b17e..29d5b1bf2 100644 --- a/src/contracts/javascript/javascriptApplicationWorkflowExamples.ts +++ b/src/contracts/javascript/javascriptApplicationWorkflowExamples.ts @@ -1,13 +1,21 @@ import { createEvidence } from "../../domain/evidence.js"; -import { reconcileJavaScriptRuntime } from "../../domain/javascript/javascriptRuntimeReconciliation.js"; +import { + parseRuntimeReconciliationInput, + reconcileJavaScriptRuntime, +} from "../../domain/javascript/javascriptRuntimeReconciliation.js"; import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE, JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE, } from "./javascriptRuntimeReconciliationExample.js"; import { createHistoricalSourceGraph } from "../../domain/referenceSourceGraph.js"; +import { reconcileJavaScriptRuntimeInputSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js"; const reconciliation = reconcileJavaScriptRuntime( - JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE, + parseRuntimeReconciliationInput( + reconcileJavaScriptRuntimeInputSchema.parse( + JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE, + ), + ), ); const reconciliationEvidence = createEvidence( undefined, diff --git a/src/domain/javascript/javascriptRuntimeReconciliation.ts b/src/domain/javascript/javascriptRuntimeReconciliation.ts index 20bdf50cc..6ad77385a 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliation.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliation.ts @@ -2,22 +2,42 @@ import { classifyStaticLoadStates } from "./javascriptRuntimeLoadState.js"; import { buildReconciledApplicationGraph } from "./javascriptRuntimeReconciliationGraph.js"; import { reconcileRuntimeEntities } from "./javascriptRuntimeReconciliationMatching.js"; import { - parseRuntimeCaptures, parseStaticLayers, + type ParsedStaticLayer, } from "./javascriptRuntimeReconciliationParsing.js"; +import { + parseRuntimeCaptures, + type ParsedRuntimeCapture, +} from "./javascriptRuntimeReconciliationCaptureParsing.js"; import { createJavaScriptRuntimeReconciliationResult } from "./javascriptRuntimeReconciliationResult.js"; import type { JavaScriptRuntimeReconciliationResult } from "./javascriptRuntimeReconciliationSchemas.js"; -import { reconcileJavaScriptRuntimeInputSchema } from "./javascriptRuntimeReconciliationSchemas.js"; +import type { ReconcileJavaScriptRuntimeInput } from "./javascriptRuntimeReconciliationSchemas.js"; import { projectRuntimeCaptures } from "./javascriptRuntimeReconciliationRuntime.js"; import { collectStaticRuntimeCandidates } from "./javascriptRuntimeStaticCandidates.js"; +/** Verified caller input and the static and runtime facts parsed from it. */ +export interface ParsedRuntimeReconciliationInput { + readonly input: ReconcileJavaScriptRuntimeInput; + readonly layers: readonly ParsedStaticLayer[]; + readonly captures: readonly ParsedRuntimeCapture[]; +} + +/** Parse caller Evidence once into the owner consumed by reconciliation. */ +export const parseRuntimeReconciliationInput = ( + input: ReconcileJavaScriptRuntimeInput, +): ParsedRuntimeReconciliationInput => ({ + input, + layers: parseStaticLayers(input.static_layers, ["static_layers"]), + captures: parseRuntimeCaptures(input.runtime_observations, [ + "runtime_observations", + ]), +}); + /** Reconcile static JAG layers with authorized passive CDP Evidence. */ export const reconcileJavaScriptRuntime = ( - input: unknown, + parsed: ParsedRuntimeReconciliationInput, ): JavaScriptRuntimeReconciliationResult => { - const parsed = reconcileJavaScriptRuntimeInputSchema.parse(input); - const layers = parseStaticLayers(parsed.static_layers); - const captures = parseRuntimeCaptures(parsed.runtime_observations); + const { layers, captures } = parsed; const runtime = projectRuntimeCaptures(captures); const candidates = collectStaticRuntimeCandidates(layers); const matching = reconcileRuntimeEntities({ diff --git a/src/domain/javascript/javascriptRuntimeReconciliationActive.ts b/src/domain/javascript/javascriptRuntimeReconciliationActive.ts index 32ef65086..4981888ed 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliationActive.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliationActive.ts @@ -3,6 +3,10 @@ import { isAbsolute } from "node:path"; import { digestCanonicalValue } from "../canonicalDigest.js"; import { isPathWithinRoot } from "../localPath.js"; import { z } from "zod"; +import { + invalidInput, + parseAtPath, +} from "./javascriptRuntimeReconciliationInputValidation.js"; import { classifyBrowserCompleteness, @@ -13,23 +17,30 @@ import { type ElectronActiveObservationResult, } from "./electronActiveObservation.js"; import type { Evidence } from "../evidence.js"; -import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationCaptureParsing.js"; /** Parse active Electron Evidence as a bounded, target-only runtime capture. */ export const parseActiveElectronCapture = ( evidence: Evidence, ): ParsedRuntimeCapture => { assertIdentity(evidence); - const result = electronActiveObservationResultSchema.parse( + const result = parseAtPath( + (value) => electronActiveObservationResultSchema.parse(value), evidence.normalized_result, + ["normalized_result"], + ); + const parameters = parseAtPath( + (value) => + z + .object({ + application_path: absolutePathSchema, + application_root: absolutePathSchema, + }) + .passthrough() + .parse(value), + evidence.parameters, + ["parameters"], ); - const parameters = z - .object({ - application_path: absolutePathSchema, - application_root: absolutePathSchema, - }) - .passthrough() - .parse(evidence.parameters); if ( result.application.application_path !== parameters.application_path || !isPathWithinRoot( @@ -37,7 +48,8 @@ export const parseActiveElectronCapture = ( result.application.application_path, ) ) - throw new TypeError( + throw invalidInput( + ["normalized_result", "application", "application_path"], "Active Electron Evidence application path disagrees with its configured root", ); return { @@ -62,11 +74,11 @@ const assertIdentity = (evidence: Evidence): void => { evidence.authority !== "controlled-replay" || evidence.confidence !== "observed" ) - throw new TypeError( + throw invalidInput( + [], "Evidence does not match the supported capture_electron_scenario contract", ); }; - const normalizeInspection = ( result: ElectronActiveObservationResult, ): { diff --git a/src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.ts b/src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.ts new file mode 100644 index 000000000..7b609b9d9 --- /dev/null +++ b/src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.ts @@ -0,0 +1,481 @@ +import { z } from "zod"; + +import { + browserAllowedOriginsSchema, + browserEndpointSchema, +} from "../browserObservation.js"; +import { + webPageInspectionSchema, + type WebPageInspection, +} from "../browserObservationSchemas.js"; +import { + classifyBrowserCompleteness, + type BrowserCompleteness, +} from "../browserCompleteness.js"; +import { + electronPageInspectionSchema, + type ElectronPageInspection, +} from "./electronObservation.js"; +import { + javascriptRuntimeObservationSchema, + javascriptRuntimeKindSchema, + type JavaScriptRuntimeObservation, + type JavaScriptRuntimeTargetLocation, +} from "./javascriptRuntimeObservation.js"; +import { digestCanonicalValue } from "../canonicalDigest.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { parseEvidence, type Evidence } from "../evidence.js"; +import { parseActiveElectronCapture } from "./javascriptRuntimeReconciliationActive.js"; +import { + assertEvidenceIdentity, + invalidInput, + parseAtPath, +} from "./javascriptRuntimeReconciliationInputValidation.js"; + +interface RuntimeCaptureBase { + readonly evidence: Evidence; + readonly captureSha256: string; + readonly scriptsCompleteWithinScope: boolean; +} + +interface NormalizedV8Inspection { + readonly target: + | { + readonly target_id: string; + readonly type: string; + readonly title: string; + readonly attached: boolean; + readonly file_path: string; + } + | { + readonly target_id: string; + readonly type: string; + readonly title: string; + readonly attached: boolean; + readonly url: string; + } + | { + readonly target_id: string; + readonly type: string; + readonly title: string; + readonly attached: boolean; + readonly unresolved_location: Extract< + JavaScriptRuntimeObservation["target"]["location"], + { kind: "unresolved" } + >; + }; + readonly frames: readonly []; + readonly scripts: { + readonly items: readonly (Readonly<{ + script_key: string; + frame_id: string | null; + cdp_hash: string | null; + length: number | null; + is_module: boolean | null; + language: null; + source: { readonly included: false; readonly reason: string }; + }> & + ( + | { readonly file_path: string } + | { readonly url: string } + | { + readonly unresolved_location: Extract< + JavaScriptRuntimeObservation["scripts"]["items"][number]["location"], + { kind: "unresolved" } + >; + } + ))[]; + }; + readonly workers: readonly []; + readonly completeness: BrowserCompleteness; +} + +export type ParsedRuntimeCapture = + | (RuntimeCaptureBase & { + readonly kind: "browser"; + readonly inspection: WebPageInspection; + }) + | (RuntimeCaptureBase & { + readonly kind: "electron"; + readonly inspection: ElectronPageInspection; + }) + | (RuntimeCaptureBase & { + readonly kind: "v8-inspector"; + readonly inspection: NormalizedV8Inspection; + }) + | (RuntimeCaptureBase & { + readonly kind: "electron-active"; + readonly inspection: { + readonly target: { + readonly target_id: string; + readonly type: string; + readonly title: string; + readonly attached: boolean; + readonly file_path: string; + }; + readonly frames: readonly []; + readonly scripts: { readonly items: readonly [] }; + readonly workers: readonly []; + readonly completeness: BrowserCompleteness; + }; + }); + +/** Parse only supported passive web/Electron inspection Evidence. */ +export const parseRuntimeCaptures = ( + observations: readonly Evidence[], + path: readonly (string | number)[] = ["runtime_observations"], +): ParsedRuntimeCapture[] => + observations + .map((observation, index) => + parseRuntimeCapture(observation, [...path, index]), + ) + .sort((left, right) => + compareUnicodeCodePoints( + left.evidence.evidence_id, + right.evidence.evidence_id, + ), + ); + +const parseRuntimeCapture = ( + input: Evidence, + evidencePath: readonly (string | number)[], +): ParsedRuntimeCapture => { + const evidence = parseAtPath(parseEvidence, input, evidencePath); + if (evidence.operation === "inspect_web_page") + return parseBrowserCapture(evidence, evidencePath); + if (evidence.operation === "inspect_electron_page") + return parseElectronCapture(evidence, evidencePath); + if (evidence.operation === "observe_javascript_runtime") + return parseV8Capture(evidence, evidencePath); + if (evidence.operation === "capture_electron_scenario") { + return parseAtPath( + () => parseActiveElectronCapture(evidence), + evidence, + evidencePath, + ); + } + throw invalidInput( + evidencePath, + "Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence", + ); +}; + +const parseBrowserCapture = ( + evidence: Evidence, + path: readonly (string | number)[], +): ParsedRuntimeCapture => { + assertEvidenceIdentity( + evidence, + { + operation: "inspect_web_page", + predicate: "rea.web-page-inspection", + providerId: "rea-cdp-browser", + providerName: "REA Chrome DevTools Protocol observation provider", + providerVersion: "2", + authority: "external-service", + confidence: "observed", + }, + path, + ); + const inspection = parseAtPath( + (value) => webPageInspectionSchema.parse(value), + evidence.normalized_result, + [...path, "normalized_result"], + ); + assertRuntimeParameters( + evidence, + { + kind: "browser", + targetId: inspection.target.target_id, + targetOrigin: inspection.target.origin, + sourceIncluded: inspection.scripts.items.some( + ({ source }) => source.included, + ), + }, + path, + ); + return { + kind: "browser", + evidence, + inspection, + captureSha256: digestCanonicalValue(inspection, "Runtime reconciliation"), + scriptsCompleteWithinScope: scriptsComplete(inspection.completeness), + }; +}; + +const parseElectronCapture = ( + evidence: Evidence, + path: readonly (string | number)[], +): ParsedRuntimeCapture => { + assertEvidenceIdentity( + evidence, + { + operation: "inspect_electron_page", + predicate: "rea.electron-page-inspection", + providerId: "rea-cdp-electron", + providerName: "REA Electron file-page CDP observation provider", + providerVersion: "1", + authority: "external-service", + confidence: "observed", + }, + path, + ); + const inspection = parseAtPath( + (value) => electronPageInspectionSchema.parse(value), + evidence.normalized_result, + [...path, "normalized_result"], + ); + assertRuntimeParameters( + evidence, + { + kind: "electron", + targetId: inspection.target.target_id, + sourceIncluded: inspection.scripts.items.some( + ({ source }) => source.included, + ), + }, + path, + ); + return { + kind: "electron", + evidence, + inspection, + captureSha256: digestCanonicalValue(inspection, "Runtime reconciliation"), + scriptsCompleteWithinScope: scriptsComplete(inspection.completeness), + }; +}; + +const parseV8Capture = ( + evidence: Evidence, + path: readonly (string | number)[], +): ParsedRuntimeCapture => { + assertEvidenceIdentity( + evidence, + { + operation: "observe_javascript_runtime", + predicate: "rea.javascript-runtime-observation", + providerId: "rea-v8-inspector", + providerName: "REA passive Node/Electron V8 Inspector provider", + providerVersion: "1", + authority: "external-service", + confidence: "observed", + }, + path, + ); + const result = parseAtPath( + (value) => javascriptRuntimeObservationSchema.parse(value), + evidence.normalized_result, + [...path, "normalized_result"], + ); + assertV8RuntimeParameters(evidence, result, path); + return { + kind: "v8-inspector", + evidence, + inspection: normalizeV8Inspection(result), + captureSha256: digestCanonicalValue(result, "Runtime reconciliation"), + scriptsCompleteWithinScope: false, + }; +}; + +const assertV8RuntimeParameters = ( + evidence: Evidence, + result: JavaScriptRuntimeObservation, + path: readonly (string | number)[], +): void => { + const parameters = parseAtPath( + (value) => + z + .object({ + inspector_endpoint: browserEndpointSchema, + target_id: z.string().trim().min(1), + runtime_kind: javascriptRuntimeKindSchema.optional(), + }) + .passthrough() + .parse(value), + evidence.parameters, + [...path, "parameters"], + ); + if ( + parameters.target_id !== result.target.target_id || + (parameters.runtime_kind !== undefined && + parameters.runtime_kind !== result.target.runtime_kind) + ) + throw invalidInput( + [...path, "parameters", "target_id"], + "Runtime Evidence target or declared role disagrees with its result", + ); + if ( + result.target.location.kind === "builtin" && + !result.target.location.specifier.startsWith("node:") + ) + throw invalidInput( + [...path, "normalized_result", "target", "location"], + "Runtime Evidence contains an invalid builtin location", + ); + for (const [index, { location }] of result.scripts.items.entries()) + if (location.kind === "builtin" && !location.specifier.startsWith("node:")) + throw invalidInput( + [...path, "normalized_result", "scripts", "items", index, "location"], + "Runtime Evidence contains an invalid builtin location", + ); +}; + +const normalizeV8Inspection = ( + result: JavaScriptRuntimeObservation, +): NormalizedV8Inspection => ({ + target: { + target_id: result.target.target_id, + type: result.target.protocol_type, + title: result.target.runtime_kind, + attached: result.target.attached, + ...(result.target.location.kind === "unresolved" + ? { unresolved_location: result.target.location } + : runtimeLocation(result.target.location)), + }, + frames: [], + scripts: { + items: result.scripts.items.map((script) => ({ + script_key: script.script_key, + frame_id: script.execution_context_key, + ...runtimeLocation(script.location), + cdp_hash: script.cdp_hash, + length: script.length, + is_module: script.is_module, + language: null, + source: { + included: false, + reason: "V8 Inspector source capture is outside passive authority.", + }, + })), + }, + workers: [], + completeness: classifyBrowserCompleteness({ + policyFilteredSections: new Set( + excludedV8Scripts(result) > 0 ? ["scripts"] : [], + ), + attachLimitedSections: new Set([ + "frames", + "scripts", + "script_sources", + "workers", + ]), + truncatedSections: new Set(result.capture.truncated ? ["scripts"] : []), + unavailableSections: new Set(["frames", "script_sources", "workers"]), + excluded: + excludedV8Scripts(result) === 0 + ? [] + : [ + { + section: "scripts", + reason: "out_of_target_scope", + count: excludedV8Scripts(result), + }, + ], + droppedEvents: { + scripts: result.capture.events_dropped, + network_requests: 0, + console_events: 0, + websocket_connections: 0, + websocket_frames: 0, + webmcp_tools: 0, + timeline_events: 0, + }, + }), +}); + +const runtimeLocation = ( + location: JavaScriptRuntimeTargetLocation, +): + | { readonly file_path: string } + | { readonly url: string } + | { + readonly unresolved_location: Extract< + JavaScriptRuntimeTargetLocation, + { kind: "unresolved" } + >; + } => { + if (location.kind === "unresolved") return { unresolved_location: location }; + if (location.kind === "file") return { file_path: location.file_path }; + if (location.kind === "url") return { url: location.sanitized_url }; + return { url: location.specifier }; +}; + +const excludedV8Scripts = (result: JavaScriptRuntimeObservation): number => + Object.values(result.scripts.excluded).reduce( + (total, count) => total + count, + 0, + ); + +const assertRuntimeParameters = ( + evidence: Evidence, + expected: + | { + readonly kind: "browser"; + readonly targetId: string; + readonly targetOrigin: string; + readonly sourceIncluded: boolean; + } + | { + readonly kind: "electron"; + readonly targetId: string; + readonly sourceIncluded: boolean; + }, + path: readonly (string | number)[], +): void => { + const common = { + target_id: z.string().trim().min(1), + cdp_endpoint: browserEndpointSchema, + include_script_sources: z.boolean(), + }; + if (expected.kind === "browser") { + const parameters = parseAtPath( + (value) => + z + .object({ ...common, allowed_origins: browserAllowedOriginsSchema }) + .passthrough() + .parse(value), + evidence.parameters, + [...path, "parameters"], + ); + if (parameters.target_id !== expected.targetId) + throw invalidInput( + [...path, "parameters", "target_id"], + "Runtime Evidence target disagrees with its captured result", + ); + if (!parameters.allowed_origins.includes(expected.targetOrigin)) + throw invalidInput( + [...path, "parameters", "allowed_origins"], + "Browser Evidence target is outside its recorded origin scope", + ); + if (expected.sourceIncluded && !parameters.include_script_sources) + throw invalidInput( + [...path, "parameters", "include_script_sources"], + "Runtime Evidence contains source without source-capture selection", + ); + return; + } + const parameters = parseAtPath( + (value) => z.object(common).passthrough().parse(value), + evidence.parameters, + [...path, "parameters"], + ); + if (parameters.target_id !== expected.targetId) + throw invalidInput( + [...path, "parameters", "target_id"], + "Runtime Evidence target disagrees with its captured result", + ); + if (expected.sourceIncluded && !parameters.include_script_sources) + throw invalidInput( + [...path, "parameters", "include_script_sources"], + "Runtime Evidence contains source without source-capture selection", + ); +}; + +const scriptsComplete = (completeness: { + readonly truncated_sections: readonly string[]; + readonly unavailable_sections: readonly string[]; + readonly dropped_events: { readonly scripts: number }; +}): boolean => + !completeness.truncated_sections.includes("scripts") && + !completeness.unavailable_sections.includes("scripts") && + completeness.dropped_events.scripts === 0; diff --git a/src/domain/javascript/javascriptRuntimeReconciliationGraph.ts b/src/domain/javascript/javascriptRuntimeReconciliationGraph.ts index 7e7067804..d3c8f371f 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliationGraph.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliationGraph.ts @@ -7,10 +7,8 @@ import type { ApplicationEdge, ApplicationNode, } from "./javascriptApplicationGraphSchemas.js"; -import type { - ParsedRuntimeCapture, - ParsedStaticLayer, -} from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedStaticLayer } from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationCaptureParsing.js"; import { uniqueSorted } from "../canonicalOrdering.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import type { RuntimeProjection } from "./javascriptRuntimeReconciliationRuntime.js"; diff --git a/src/domain/javascript/javascriptRuntimeReconciliationInputValidation.ts b/src/domain/javascript/javascriptRuntimeReconciliationInputValidation.ts new file mode 100644 index 000000000..7b303b3e4 --- /dev/null +++ b/src/domain/javascript/javascriptRuntimeReconciliationInputValidation.ts @@ -0,0 +1,57 @@ +import { z } from "zod"; +import type { Evidence } from "../evidence.js"; + +/** Prefix caller paths on a nested Zod validation boundary. */ +export const parseAtPath = ( + parse: (input: unknown) => Value, + input: unknown, + path: readonly (string | number)[], +): Value => { + try { + return parse(input); + } catch (cause: unknown) { + if (cause instanceof z.ZodError) + throw new z.ZodError( + cause.issues.map((issue) => ({ + ...issue, + path: [...path, ...issue.path], + })), + ); + throw cause; + } +}; + +/** Represent one semantic caller constraint as a standard validation issue. */ +export const invalidInput = ( + path: readonly (string | number)[], + message: string, +): z.ZodError => new z.ZodError([{ code: "custom", path: [...path], message }]); + +/** Verify an authenticated Evidence record against one runtime workflow. */ +export const assertEvidenceIdentity = ( + evidence: Evidence, + expected: { + readonly operation: string; + readonly predicate: string; + readonly providerId: string; + readonly providerName: string; + readonly providerVersion: string; + readonly authority: Evidence["authority"]; + readonly confidence: Evidence["confidence"]; + }, + path: readonly (string | number)[], +): void => { + if ( + evidence.operation !== expected.operation || + evidence.predicate_type !== expected.predicate || + evidence.provider.id !== expected.providerId || + evidence.provider.name !== expected.providerName || + evidence.provider.version !== expected.providerVersion || + evidence.authority !== expected.authority || + evidence.confidence !== expected.confidence + ) + throw invalidInput( + path, + `Evidence does not match the supported ${expected.operation} contract`, + ); +}; diff --git a/src/domain/javascript/javascriptRuntimeReconciliationParsing.ts b/src/domain/javascript/javascriptRuntimeReconciliationParsing.ts index 4c4310341..afae44998 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliationParsing.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliationParsing.ts @@ -1,27 +1,3 @@ -import { z } from "zod"; - -import { - browserAllowedOriginsSchema, - browserEndpointSchema, -} from "../browserObservation.js"; -import { - webPageInspectionSchema, - type WebPageInspection, -} from "../browserObservationSchemas.js"; -import { - classifyBrowserCompleteness, - type BrowserCompleteness, -} from "../browserCompleteness.js"; -import { - electronPageInspectionSchema, - type ElectronPageInspection, -} from "./electronObservation.js"; -import { - javascriptRuntimeObservationSchema, - javascriptRuntimeKindSchema, - type JavaScriptRuntimeObservation, - type JavaScriptRuntimeTargetLocation, -} from "./javascriptRuntimeObservation.js"; import { digestCanonicalValue } from "../canonicalDigest.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { parseEvidence, type Evidence } from "../evidence.js"; @@ -29,9 +5,13 @@ import { javascriptApplicationAnalysisResultSchema, type JavaScriptApplicationAnalysisResult, } from "./javascriptApplicationAnalysis.js"; -import { type JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js"; -import { parseActiveElectronCapture } from "./javascriptRuntimeReconciliationActive.js"; +import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js"; import type { ReconcileJavaScriptRuntimeInput } from "./javascriptRuntimeReconciliationSchemas.js"; +import { + assertEvidenceIdentity, + invalidInput, + parseAtPath, +} from "./javascriptRuntimeReconciliationInputValidation.js"; type StaticLayerInput = ReconcileJavaScriptRuntimeInput["static_layers"][number]; @@ -46,138 +26,50 @@ export interface ParsedStaticLayer { readonly runtimeMappings: readonly RuntimeMapping[]; } -interface RuntimeCaptureBase { - readonly evidence: Evidence; - readonly captureSha256: string; - readonly scriptsCompleteWithinScope: boolean; -} - -interface NormalizedV8Inspection { - readonly target: - | { - readonly target_id: string; - readonly type: string; - readonly title: string; - readonly attached: boolean; - readonly file_path: string; - } - | { - readonly target_id: string; - readonly type: string; - readonly title: string; - readonly attached: boolean; - readonly url: string; - } - | { - readonly target_id: string; - readonly type: string; - readonly title: string; - readonly attached: boolean; - readonly unresolved_location: Extract< - JavaScriptRuntimeObservation["target"]["location"], - { kind: "unresolved" } - >; - }; - readonly frames: readonly []; - readonly scripts: { - readonly items: readonly (Readonly<{ - script_key: string; - frame_id: string | null; - cdp_hash: string | null; - length: number | null; - is_module: boolean | null; - language: null; - source: { readonly included: false; readonly reason: string }; - }> & - ( - | { readonly file_path: string } - | { readonly url: string } - | { - readonly unresolved_location: Extract< - JavaScriptRuntimeObservation["scripts"]["items"][number]["location"], - { kind: "unresolved" } - >; - } - ))[]; - }; - readonly workers: readonly []; - readonly completeness: BrowserCompleteness; -} - -export type ParsedRuntimeCapture = - | (RuntimeCaptureBase & { - readonly kind: "browser"; - readonly inspection: WebPageInspection; - }) - | (RuntimeCaptureBase & { - readonly kind: "electron"; - readonly inspection: ElectronPageInspection; - }) - | (RuntimeCaptureBase & { - readonly kind: "v8-inspector"; - readonly inspection: NormalizedV8Inspection; - }) - | (RuntimeCaptureBase & { - readonly kind: "electron-active"; - readonly inspection: { - readonly target: { - readonly target_id: string; - readonly type: string; - readonly title: string; - readonly attached: boolean; - readonly file_path: string; - }; - readonly frames: readonly []; - readonly scripts: { readonly items: readonly [] }; - readonly workers: readonly []; - readonly completeness: BrowserCompleteness; - }; - }); - /** Parse and semantically bind every static analysis Evidence layer. */ export const parseStaticLayers = ( layers: readonly StaticLayerInput[], + path: readonly (string | number)[] = ["static_layers"], ): ParsedStaticLayer[] => layers - .map((layer) => parseStaticLayer(layer)) + .map((layer, index) => + parseStaticLayer(layer, [...path, index, "analysis"]), + ) .sort((left, right) => compareUnicodeCodePoints(left.layerId, right.layerId), ); -/** Parse only supported passive web/Electron inspection Evidence. */ -export const parseRuntimeCaptures = ( - observations: readonly Evidence[], -): ParsedRuntimeCapture[] => - observations - .map((observation) => parseRuntimeCapture(observation)) - .sort((left, right) => - compareUnicodeCodePoints( - left.evidence.evidence_id, - right.evidence.evidence_id, - ), - ); - -const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => { - const evidence = parseEvidence(layer.analysis); - const result = javascriptApplicationAnalysisResultSchema.parse( +const parseStaticLayer = ( + layer: StaticLayerInput, + evidencePath: readonly (string | number)[], +): ParsedStaticLayer => { + const evidence = parseAtPath(parseEvidence, layer.analysis, evidencePath); + const result = parseAtPath( + (value) => javascriptApplicationAnalysisResultSchema.parse(value), evidence.normalized_result, + [...evidencePath, "normalized_result"], + ); + assertEvidenceIdentity( + evidence, + { + operation: "analyze_javascript_application", + predicate: "rea.javascript-application-analysis", + providerId: "rea-javascript-application", + providerName: "REA JavaScript application analyzer", + providerVersion: "1", + authority: "shipped-artifact", + confidence: "derived", + }, + evidencePath, ); - assertEvidenceIdentity(evidence, { - operation: "analyze_javascript_application", - predicate: "rea.javascript-application-analysis", - providerId: "rea-javascript-application", - providerName: "REA JavaScript application analyzer", - providerVersion: "1", - authority: "shipped-artifact", - confidence: "derived", - }); if ( evidence.subject === null || evidence.subject.digest.sha256 !== result.root_artifact_sha256 || evidence.subject.format !== result.format || evidence.subject.local_path !== result.input_path ) - throw new TypeError( + throw invalidInput( + [...evidencePath, "subject"], "JavaScript application Evidence subject disagrees with its result", ); return { @@ -196,294 +88,3 @@ const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => { runtimeMappings: layer.runtime_mappings, }; }; - -const parseRuntimeCapture = (input: Evidence): ParsedRuntimeCapture => { - const evidence = parseEvidence(input); - if (evidence.operation === "inspect_web_page") { - assertEvidenceIdentity(evidence, { - operation: "inspect_web_page", - predicate: "rea.web-page-inspection", - providerId: "rea-cdp-browser", - providerName: "REA Chrome DevTools Protocol observation provider", - providerVersion: "2", - authority: "external-service", - confidence: "observed", - }); - const inspection = webPageInspectionSchema.parse( - evidence.normalized_result, - ); - assertRuntimeParameters(evidence, { - kind: "browser", - targetId: inspection.target.target_id, - targetOrigin: inspection.target.origin, - sourceIncluded: inspection.scripts.items.some( - ({ source }) => source.included, - ), - }); - return { - kind: "browser", - evidence, - inspection, - captureSha256: digestCanonicalValue(inspection, "Runtime reconciliation"), - scriptsCompleteWithinScope: scriptsComplete(inspection.completeness), - }; - } - if (evidence.operation === "inspect_electron_page") { - assertEvidenceIdentity(evidence, { - operation: "inspect_electron_page", - predicate: "rea.electron-page-inspection", - providerId: "rea-cdp-electron", - providerName: "REA Electron file-page CDP observation provider", - providerVersion: "1", - authority: "external-service", - confidence: "observed", - }); - const inspection = electronPageInspectionSchema.parse( - evidence.normalized_result, - ); - assertRuntimeParameters(evidence, { - kind: "electron", - targetId: inspection.target.target_id, - sourceIncluded: inspection.scripts.items.some( - ({ source }) => source.included, - ), - }); - return { - kind: "electron", - evidence, - inspection, - captureSha256: digestCanonicalValue(inspection, "Runtime reconciliation"), - scriptsCompleteWithinScope: scriptsComplete(inspection.completeness), - }; - } - if (evidence.operation === "observe_javascript_runtime") { - assertEvidenceIdentity(evidence, { - operation: "observe_javascript_runtime", - predicate: "rea.javascript-runtime-observation", - providerId: "rea-v8-inspector", - providerName: "REA passive Node/Electron V8 Inspector provider", - providerVersion: "1", - authority: "external-service", - confidence: "observed", - }); - const result = javascriptRuntimeObservationSchema.parse( - evidence.normalized_result, - ); - assertV8RuntimeParameters(evidence, result); - const inspection = normalizeV8Inspection(result); - return { - kind: "v8-inspector", - evidence, - inspection, - captureSha256: digestCanonicalValue(result, "Runtime reconciliation"), - scriptsCompleteWithinScope: false, - }; - } - if (evidence.operation === "capture_electron_scenario") { - return parseActiveElectronCapture(evidence); - } - throw new TypeError( - "Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence", - ); -}; - -const assertV8RuntimeParameters = ( - evidence: Evidence, - result: JavaScriptRuntimeObservation, -): void => { - const parameters = z - .object({ - inspector_endpoint: browserEndpointSchema, - target_id: z.string().trim().min(1), - runtime_kind: javascriptRuntimeKindSchema.optional(), - }) - .passthrough() - .parse(evidence.parameters); - if ( - parameters.target_id !== result.target.target_id || - (parameters.runtime_kind !== undefined && - parameters.runtime_kind !== result.target.runtime_kind) - ) - throw new TypeError( - "Runtime Evidence target or declared role disagrees with its result", - ); - for (const location of [ - result.target.location, - ...result.scripts.items.map(({ location }) => location), - ]) - if (location.kind === "builtin" && !location.specifier.startsWith("node:")) - throw new TypeError( - "Runtime Evidence contains an invalid builtin location", - ); -}; - -const normalizeV8Inspection = ( - result: JavaScriptRuntimeObservation, -): NormalizedV8Inspection => ({ - target: { - target_id: result.target.target_id, - type: result.target.protocol_type, - title: result.target.runtime_kind, - attached: result.target.attached, - ...(result.target.location.kind === "unresolved" - ? { unresolved_location: result.target.location } - : runtimeLocation(result.target.location)), - }, - frames: [], - scripts: { - items: result.scripts.items.map((script) => ({ - script_key: script.script_key, - frame_id: script.execution_context_key, - ...runtimeLocation(script.location), - cdp_hash: script.cdp_hash, - length: script.length, - is_module: script.is_module, - language: null, - source: { - included: false, - reason: "V8 Inspector source capture is outside passive authority.", - }, - })), - }, - workers: [], - completeness: classifyBrowserCompleteness({ - policyFilteredSections: new Set( - excludedV8Scripts(result) > 0 ? ["scripts"] : [], - ), - attachLimitedSections: new Set([ - "frames", - "scripts", - "script_sources", - "workers", - ]), - truncatedSections: new Set(result.capture.truncated ? ["scripts"] : []), - unavailableSections: new Set(["frames", "script_sources", "workers"]), - excluded: - excludedV8Scripts(result) === 0 - ? [] - : [ - { - section: "scripts", - reason: "out_of_target_scope", - count: excludedV8Scripts(result), - }, - ], - droppedEvents: { - scripts: result.capture.events_dropped, - network_requests: 0, - console_events: 0, - websocket_connections: 0, - websocket_frames: 0, - webmcp_tools: 0, - timeline_events: 0, - }, - }), -}); - -const runtimeLocation = ( - location: JavaScriptRuntimeTargetLocation, -): - | { readonly file_path: string } - | { readonly url: string } - | { - readonly unresolved_location: Extract< - JavaScriptRuntimeTargetLocation, - { kind: "unresolved" } - >; - } => { - if (location.kind === "unresolved") return { unresolved_location: location }; - if (location.kind === "file") return { file_path: location.file_path }; - if (location.kind === "url") return { url: location.sanitized_url }; - return { url: location.specifier }; -}; - -const excludedV8Scripts = (result: JavaScriptRuntimeObservation): number => - Object.values(result.scripts.excluded).reduce( - (total, count) => total + count, - 0, - ); - -const assertRuntimeParameters = ( - evidence: Evidence, - expected: - | { - readonly kind: "browser"; - readonly targetId: string; - readonly targetOrigin: string; - readonly sourceIncluded: boolean; - } - | { - readonly kind: "electron"; - readonly targetId: string; - readonly sourceIncluded: boolean; - }, -): void => { - const common = { - target_id: z.string().trim().min(1), - cdp_endpoint: browserEndpointSchema, - include_script_sources: z.boolean(), - }; - if (expected.kind === "browser") { - const parameters = z - .object({ ...common, allowed_origins: browserAllowedOriginsSchema }) - .passthrough() - .parse(evidence.parameters); - if (parameters.target_id !== expected.targetId) - throw new TypeError( - "Runtime Evidence target disagrees with its captured result", - ); - if (!parameters.allowed_origins.includes(expected.targetOrigin)) - throw new TypeError( - "Browser Evidence target is outside its recorded origin scope", - ); - if (expected.sourceIncluded && !parameters.include_script_sources) - throw new TypeError( - "Runtime Evidence contains source without source-capture selection", - ); - return; - } - const parameters = z.object(common).passthrough().parse(evidence.parameters); - if (parameters.target_id !== expected.targetId) - throw new TypeError( - "Runtime Evidence target disagrees with its captured result", - ); - if (expected.sourceIncluded && !parameters.include_script_sources) - throw new TypeError( - "Runtime Evidence contains source without source-capture selection", - ); -}; - -const scriptsComplete = (completeness: { - readonly truncated_sections: readonly string[]; - readonly unavailable_sections: readonly string[]; - readonly dropped_events: { readonly scripts: number }; -}): boolean => - !completeness.truncated_sections.includes("scripts") && - !completeness.unavailable_sections.includes("scripts") && - completeness.dropped_events.scripts === 0; - -const assertEvidenceIdentity = ( - evidence: Evidence, - expected: { - readonly operation: string; - readonly predicate: string; - readonly providerId: string; - readonly providerName: string; - readonly providerVersion: string; - readonly authority: Evidence["authority"]; - readonly confidence: Evidence["confidence"]; - }, -): void => { - if ( - evidence.operation !== expected.operation || - evidence.predicate_type !== expected.predicate || - evidence.provider.id !== expected.providerId || - evidence.provider.name !== expected.providerName || - evidence.provider.version !== expected.providerVersion || - evidence.authority !== expected.authority || - evidence.confidence !== expected.confidence - ) - throw new TypeError( - `Evidence does not match the supported ${expected.operation} contract`, - ); -}; diff --git a/src/domain/javascript/javascriptRuntimeReconciliationResult.ts b/src/domain/javascript/javascriptRuntimeReconciliationResult.ts index a814deae1..19226f27c 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliationResult.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliationResult.ts @@ -3,10 +3,8 @@ import { digestCanonicalValue } from "../canonicalDigest.js"; import { uniqueSorted } from "../canonicalOrdering.js"; import type { StaticLoadStateProjection } from "./javascriptRuntimeLoadState.js"; import type { RuntimeMatchingProjection } from "./javascriptRuntimeReconciliationMatching.js"; -import type { - ParsedRuntimeCapture, - ParsedStaticLayer, -} from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedStaticLayer } from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationCaptureParsing.js"; import { javascriptRuntimeReconciliationResultSchema, type JavaScriptRuntimeReconciliationResult, diff --git a/src/domain/javascript/javascriptRuntimeReconciliationRuntime.ts b/src/domain/javascript/javascriptRuntimeReconciliationRuntime.ts index 7d9cfd42c..8c0137701 100644 --- a/src/domain/javascript/javascriptRuntimeReconciliationRuntime.ts +++ b/src/domain/javascript/javascriptRuntimeReconciliationRuntime.ts @@ -8,7 +8,7 @@ import type { ApplicationNode, } from "./javascriptApplicationGraphSchemas.js"; import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js"; -import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationParsing.js"; +import type { ParsedRuntimeCapture } from "./javascriptRuntimeReconciliationCaptureParsing.js"; export interface RuntimeReconciliationEntity { readonly kind: "target" | "frame" | "script" | "worker"; diff --git a/tests/boundary/browser/cdpScriptMetadata.test.ts b/tests/boundary/browser/cdpScriptMetadata.test.ts index 5f6f3ce4e..37b1eb13f 100644 --- a/tests/boundary/browser/cdpScriptMetadata.test.ts +++ b/tests/boundary/browser/cdpScriptMetadata.test.ts @@ -12,7 +12,7 @@ import { publishWebScripts } from "../../../src/browser/assets/PublishWebScripts import { selectScriptCapture } from "../../../src/browser/assets/ScriptCaptureAdapters.js"; import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js"; import { inspectElectronPageInputSchema } from "../../../src/domain/javascript/electronObservation.js"; -import { parseRuntimeCaptures } from "../../../src/domain/javascript/javascriptRuntimeReconciliationParsing.js"; +import { parseRuntimeCaptures } from "../../../src/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.js"; import { projectRuntimeCaptures } from "../../../src/domain/javascript/javascriptRuntimeReconciliationRuntime.js"; import { V8InspectorProvider } from "../../../src/inspector/V8InspectorProvider.js"; import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js"; diff --git a/tests/boundary/inspector/javascriptRuntimeObservation.test.ts b/tests/boundary/inspector/javascriptRuntimeObservation.test.ts index 149d6e833..4dd561240 100644 --- a/tests/boundary/inspector/javascriptRuntimeObservation.test.ts +++ b/tests/boundary/inspector/javascriptRuntimeObservation.test.ts @@ -5,11 +5,13 @@ import { pathToFileURL } from "node:url"; import { describe, expect, test } from "vitest"; import { createJavaScriptRuntimeObservationEvidence } from "../../../src/application/javascript/JavaScriptRuntimeObservationEvidence.js"; +import { createBrowserEvidence } from "../../../src/application/BrowserEvidence.js"; import { listJavaScriptRuntimeTargets, observeJavaScriptRuntime, } from "../../../src/application/javascript/JavaScriptRuntimeObservationService.js"; import { reconcileJavaScriptRuntimeEvidence } from "../../../src/application/javascript/JavaScriptRuntimeReconciliationService.js"; +import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js"; import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/inspector/providerIdentity.js"; import { V8InspectorProvider } from "../../../src/inspector/V8InspectorProvider.js"; import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js"; @@ -18,10 +20,102 @@ import type { ObserveJavaScriptRuntimeInput, } from "../../../src/domain/javascript/javascriptRuntimeObservation.js"; import { observeJavaScriptRuntimeInputSchema } from "../../../src/domain/javascript/javascriptRuntimeObservation.js"; +import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js"; +import { createEvidence } from "../../../src/domain/evidence.js"; import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { startFakeV8Inspector } from "../../fixtures/inspector/fakeV8Inspector.js"; +import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +test("reports static-layer Evidence digest failure at its caller path", () => { + const layer = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers[0]; + if (layer === undefined) throw new Error("Expected a static layer example"); + const runtime = createJavaScriptRuntimeObservationEvidence( + "observe_javascript_runtime", + { + inspector_endpoint: "http://127.0.0.1:9229", + target_id: "example-v8-target", + runtime_kind: "electron-main", + observation_ms: 100, + }, + runtimeObservation("/tmp/index.html", "/tmp/main.js"), + V8_INSPECTOR_PROVIDER_IDENTITY, + ); + const result = reconcileJavaScriptRuntimeEvidence({ + static_layers: [ + { + ...layer, + analysis: { ...layer.analysis, evidence_id: `ev_${"0".repeat(64)}` }, + }, + ], + runtime_observations: [runtime], + }); + expect(result).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisInputError", + issues: [ + { + path: ["static_layers", 0, "analysis", "evidence_id"], + reason: "invalid_value", + message: "Evidence semantic identifier does not match its record", + }, + ], + }, + }); +}); + +test("reports browser origin scope mismatch at the caller parameter path", async () => { + const browser = await startFakeCdpBrowser(); + try { + const provider = new CdpBrowserProvider(); + const input = inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 0, + }); + const observed = await provider.inspectPage(input); + if (!observed.ok) throw observed.error; + const evidence = createBrowserEvidence( + "inspect_web_page", + input, + observed.value, + provider.identity(), + ); + const invalidEvidence = createEvidence(undefined, evidence.provider, { + predicateType: evidence.predicate_type, + operation: evidence.operation, + parameters: { ...evidence.parameters, allowed_origins: [] }, + result: evidence.normalized_result, + confidence: evidence.confidence, + authority: evidence.authority, + environment: evidence.environment, + limitations: evidence.limitations, + }); + const result = reconcileJavaScriptRuntimeEvidence({ + static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers, + runtime_observations: [invalidEvidence], + }); + expect(result).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisInputError", + issues: [ + { + path: ["runtime_observations", 0, "parameters", "allowed_origins"], + reason: "invalid_value", + message: + "Browser Evidence target is outside its recorded origin scope", + }, + ], + }, + }); + } finally { + await browser.close(); + } +}); + describe("Inspector execution-context lifecycle metadata", () => { test.each([ [ diff --git a/tests/boundary/inspector/javascriptRuntimeUnresolvedTarget.test.ts b/tests/boundary/inspector/javascriptRuntimeUnresolvedTarget.test.ts index d56518032..cfc47a735 100644 --- a/tests/boundary/inspector/javascriptRuntimeUnresolvedTarget.test.ts +++ b/tests/boundary/inspector/javascriptRuntimeUnresolvedTarget.test.ts @@ -7,10 +7,21 @@ import { expect, test } from "vitest"; import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js"; import { createJavaScriptRuntimeObservationEvidence } from "../../../src/application/javascript/JavaScriptRuntimeObservationEvidence.js"; import { V8InspectorProvider } from "../../../src/inspector/V8InspectorProvider.js"; -import { reconcileJavaScriptRuntime } from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { + parseRuntimeReconciliationInput, + reconcileJavaScriptRuntime, +} from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { reconcileJavaScriptRuntimeInputSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { startFakeV8Inspector } from "../../fixtures/inspector/fakeV8Inspector.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +const reconcileInput = (input: unknown) => + reconcileJavaScriptRuntime( + parseRuntimeReconciliationInput( + reconcileJavaScriptRuntimeInputSchema.parse(input), + ), + ); + test("keeps unresolved target identity unknown while matching verified loaded scripts", async () => { const root = await createTestTempDirectory("rea-unresolved-runtime-"); const entry = join(root, "entry.js"); @@ -37,7 +48,7 @@ test("keeps unresolved target identity unknown while matching verified loaded sc observed.value, provider.identity(), ); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [{ role: "application", analysis: analysis.value }], runtime_observations: [evidence], }); diff --git a/tests/boundary/process/javascriptRuntimeReconciliationAmbiguity.test.ts b/tests/boundary/process/javascriptRuntimeReconciliationAmbiguity.test.ts index 7d61829ae..3d709e3c7 100644 --- a/tests/boundary/process/javascriptRuntimeReconciliationAmbiguity.test.ts +++ b/tests/boundary/process/javascriptRuntimeReconciliationAmbiguity.test.ts @@ -9,10 +9,21 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createElectronEvidence } from "../../../src/application/javascript/ElectronEvidence.js"; import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js"; -import { reconcileJavaScriptRuntime } from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { + parseRuntimeReconciliationInput, + reconcileJavaScriptRuntime, +} from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { reconcileJavaScriptRuntimeInputSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { inspectElectronPageInputSchema } from "../../../src/domain/javascript/electronObservation.js"; import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js"; +const reconcileInput = (input: unknown) => + reconcileJavaScriptRuntime( + parseRuntimeReconciliationInput( + reconcileJavaScriptRuntimeInputSchema.parse(input), + ), + ); + const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`; const execute = promisify(execFile); @@ -36,7 +47,7 @@ it("keeps byte-identical cross-layer candidates explicitly ambiguous", async () writeFile(join(runtime, "app.js"), SOURCE), writeFile(join(runtime, "index.html"), ""), ]); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [ { role: "application", @@ -82,7 +93,7 @@ it("retains all runtime entities and static load states without projection caps" }), ]; - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [{ role: "application", analysis: staticEvidence }], runtime_observations: runtimeObservations, }); @@ -121,7 +132,7 @@ it("rejects runtime source bytes whose Evidence omits source-capture approval", }); expect(() => - reconcileJavaScriptRuntime({ + reconcileInput({ static_layers: [{ role: "application", analysis: staticEvidence }], runtime_observations: [contradictoryRuntime], }), @@ -131,7 +142,7 @@ it("rejects runtime source bytes whose Evidence omits source-capture approval", it("keeps graph omission counts unknown when a runtime section is unavailable", async () => { const fixture = await applicationFixture(); temporary.push(fixture); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [ { role: "application", analysis: await analyzeFixture(fixture) }, ], diff --git a/tests/composition/runtime-observation/javascriptRuntimeReconciliation.test.ts b/tests/composition/runtime-observation/javascriptRuntimeReconciliation.test.ts index 1fe3f2756..a6809156e 100644 --- a/tests/composition/runtime-observation/javascriptRuntimeReconciliation.test.ts +++ b/tests/composition/runtime-observation/javascriptRuntimeReconciliation.test.ts @@ -8,20 +8,71 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createElectronEvidence } from "../../../src/application/javascript/ElectronEvidence.js"; import { createElectronActiveEvidence } from "../../../src/application/javascript/ElectronActiveEvidence.js"; import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js"; -import { reconcileJavaScriptRuntime } from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { reconcileJavaScriptRuntimeEvidence } from "../../../src/application/javascript/JavaScriptRuntimeReconciliationService.js"; +import { createEvidence } from "../../../src/domain/evidence.js"; +import { + parseRuntimeReconciliationInput, + reconcileJavaScriptRuntime, +} from "../../../src/domain/javascript/javascriptRuntimeReconciliation.js"; +import { reconcileJavaScriptRuntimeInputSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js"; import { electronActiveObservationInputSchema } from "../../../src/domain/javascript/electronActiveObservation.js"; import { inspectElectronPageInputSchema } from "../../../src/domain/javascript/electronObservation.js"; import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js"; import { createElectronActiveObservationFixtureResult } from "../../../src/domain/javascript/electronActiveObservation.fixture.js"; +const reconcileInput = (input: unknown) => + reconcileJavaScriptRuntime( + parseRuntimeReconciliationInput( + reconcileJavaScriptRuntimeInputSchema.parse(input), + ), + ); + const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`; +it("preserves source-capture input paths for runtime Evidence", async () => { + const root = await applicationFixture(); + const application = await analyzeFixture(root); + const runtime = electronRuntimeEvidence(root, SOURCE); + const invalidRuntime = createEvidence(undefined, runtime.provider, { + predicateType: runtime.predicate_type, + operation: runtime.operation, + parameters: { ...runtime.parameters, include_script_sources: false }, + result: runtime.normalized_result, + confidence: runtime.confidence, + authority: runtime.authority, + }); + + const result = reconcileJavaScriptRuntimeEvidence({ + static_layers: [{ role: "application", analysis: application }], + runtime_observations: [invalidRuntime], + }); + expect(result).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisInputError", + issues: [ + { + path: [ + "runtime_observations", + 0, + "parameters", + "include_script_sources", + ], + reason: "invalid_value", + message: + "Runtime Evidence contains source without source-capture selection", + }, + ], + }, + }); +}); + it("reconciles runtime scripts inside dot-prefixed child directories", async () => { const root = await applicationFixture(); await mkdir(join(root, "..cache")); await writeFile(join(root, "..cache", "app.js"), SOURCE); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [ { role: "application", analysis: await analyzeFixture(root) }, ], @@ -48,7 +99,7 @@ it("matches renderer, frame, script bytes, and worker without claiming execution const staticEvidence = await analyzeFixture(fixture); const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [{ role: "application", analysis: staticEvidence }], runtime_observations: [runtimeEvidence], }); @@ -143,7 +194,7 @@ it("reports a captured digest disagreement instead of accepting a path match", a "export const observed = 'different';\n", ); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [{ role: "application", analysis: staticEvidence }], runtime_observations: [runtimeEvidence], }); @@ -181,7 +232,7 @@ it("reconciles active Electron as a partial target-only runtime capture", async }, ); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [{ role: "application", analysis: staticEvidence }], runtime_observations: [runtimeEvidence], }); @@ -280,7 +331,7 @@ it("imports an operator-provided cache layer through an explicit file mapping", includeWorker: false, }); - const result = reconcileJavaScriptRuntime({ + const result = reconcileInput({ static_layers: [ { role: "application", analysis: applicationEvidence }, { From d761d7358b45fe0724b182a206241fd605f338b0 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:27:39 +0800 Subject: [PATCH 076/189] test(ghidra): allow rollback tests to reach spawned process --- tests/boundary/providers/ghidra/ghidraClient.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/tests/boundary/providers/ghidra/ghidraClient.test.ts b/tests/boundary/providers/ghidra/ghidraClient.test.ts index a8a7eeac8..ac2e5cbc1 100644 --- a/tests/boundary/providers/ghidra/ghidraClient.test.ts +++ b/tests/boundary/providers/ghidra/ghidraClient.test.ts @@ -766,7 +766,6 @@ describe.skipIf(process.platform === "win32")( const controller = new AbortController(); let cleanupAllowed = false; - let cleanupAttempts = 0; let child: ChildProcess | undefined; let runtimeRoot: string | undefined; const headless = new GhidraHeadlessLauncher({ @@ -798,7 +797,6 @@ describe.skipIf(process.platform === "win32")( expectedParentPid: process.pid, }, cleanup: async () => { - cleanupAttempts += 1; if (!cleanupAllowed) return { cleaned: false as const, @@ -825,7 +823,7 @@ describe.skipIf(process.platform === "win32")( return headless.launch(session, options); }, }; - const client = clientFor(launcher); + const client = clientFor(launcher, { startupTimeoutMs: 10_000 }); onTestFinished(async () => { cleanupAllowed = true; await client.close(); @@ -852,11 +850,9 @@ describe.skipIf(process.platform === "win32")( await access(runtimeRoot); expect(child.exitCode).toBeNull(); expect(child.signalCode).toBeNull(); - expect(cleanupAttempts).toBe(2); cleanupAllowed = true; await expect(client.close()).resolves.toEqual(ok(null)); - expect(cleanupAttempts).toBe(3); await expect(access(runtimeRoot)).rejects.toMatchObject({ code: "ENOENT", }); From 961c3c3de79ec44d608d011eb3fa3d6bd645cf6a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:31:00 +0800 Subject: [PATCH 077/189] test(android): allow provider readiness under load --- tests/boundary/process/androidAnalysisMcp.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/boundary/process/androidAnalysisMcp.test.ts b/tests/boundary/process/androidAnalysisMcp.test.ts index d0179f3c5..14a301775 100644 --- a/tests/boundary/process/androidAnalysisMcp.test.ts +++ b/tests/boundary/process/androidAnalysisMcp.test.ts @@ -307,7 +307,7 @@ it("cleans an active engine when the MCP client disconnects", async () => { const pending = client .callTool({ name: "inspect_android_package", arguments: { path: apk } }) .catch(() => undefined); - await expect.poll(() => launches.length).toBe(1); + await expect.poll(() => launches.length, { timeout: 10_000 }).toBe(1); await client.close(); await pending; await expect From 79d5b9a826b9204c1ef59b0a5c5ec83e7a2f2bec Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:43:26 +0800 Subject: [PATCH 078/189] test(process): report cleanup details on cancellation failures --- .../process/processCaptureCancellationAdapters.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/boundary/process/processCaptureCancellationAdapters.test.ts b/tests/boundary/process/processCaptureCancellationAdapters.test.ts index 7a7159e91..694f83409 100644 --- a/tests/boundary/process/processCaptureCancellationAdapters.test.ts +++ b/tests/boundary/process/processCaptureCancellationAdapters.test.ts @@ -8,6 +8,7 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import pino from "pino"; import { expect, onTestFinished } from "vitest"; import { z } from "zod"; +import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { createServer } from "../../../src/server/createServer.js"; import { @@ -124,7 +125,8 @@ itWithCaptureCapability.each(["SIGINT", "SIGTERM"] as const)( await expect(access(join(root, "late-write"))).rejects.toMatchObject({ code: "ENOENT", }); - expect(JSON.parse(stdout)).toMatchObject({ + const result = analysisCliErrorEnvelopeSchema.parse(JSON.parse(stdout)); + expect(result, JSON.stringify(result.details)).toMatchObject({ code: "cancelled", details: { operation: "process_capture", cleanup: "complete" }, }); From 5d32e4252941e93065cadd83b9f02aa6427544d8 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:53:12 +0800 Subject: [PATCH 079/189] test(cli): remove duplicate malformed JSON assertion --- tests/boundary/filesystem/cliJsonInput.test.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts index 9a8c93d89..1116bf892 100644 --- a/tests/boundary/filesystem/cliJsonInput.test.ts +++ b/tests/boundary/filesystem/cliJsonInput.test.ts @@ -160,12 +160,6 @@ describe("CLI JSON input", () => { }, 20_000); it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => { - expect(await parseCliJsonInput("[", "test-input")).toMatchObject({ - ok: false, - error: { - details: { issues: [{ reason: "invalid_format", expected: "JSON" }] }, - }, - }); expect(await parseCliJsonInput("[", "test-input")).toMatchObject({ ok: false, error: { From ca9010936a934a49fbc6cf69eb1d7fc2242b6da9 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:02:40 +0800 Subject: [PATCH 080/189] test(package): share validated native dossier fixtures --- scripts/fixtures/function-dossier.mjs | 35 ++++++++++++++++++++++++++ scripts/lib/verify-package-core.mjs | 29 --------------------- scripts/verify-package-managed.mjs | 3 ++- scripts/verify/managed/config.mjs | 34 ------------------------- scripts/verify/managed/conformance.mjs | 2 +- tests/fixtures/fakeHopper.mjs | 8 ++++++ 6 files changed, 46 insertions(+), 65 deletions(-) create mode 100644 scripts/fixtures/function-dossier.mjs diff --git a/scripts/fixtures/function-dossier.mjs b/scripts/fixtures/function-dossier.mjs new file mode 100644 index 000000000..c1b0cd0f5 --- /dev/null +++ b/scripts/fixtures/function-dossier.mjs @@ -0,0 +1,35 @@ +import { functionDossierSchema } from "../../dist/domain/hopperValues.js"; + +/** Validated synthetic native observations shared by managed verification lanes. */ +export const functionDossier = (name) => + functionDossierSchema.parse({ + procedure: { + address: "0x401000", + name, + classification: { + external: false, + thunk: false, + thunk_target: null, + provenance: "synthetic-provider", + }, + body: { + available: false, + reason: "Synthetic provider does not supply function body ranges.", + }, + signature: null, + locals: [], + }, + pseudocode: "", + assembly: [], + comments: [], + callers: [], + callees: [], + incoming_references: [], + outgoing_references: [], + referenced_strings: [], + referenced_names: [], + basic_blocks: [], + native_api: null, + native_value_flow: null, + limitations: [], + }); diff --git a/scripts/lib/verify-package-core.mjs b/scripts/lib/verify-package-core.mjs index 417cc14a1..5371edffc 100644 --- a/scripts/lib/verify-package-core.mjs +++ b/scripts/lib/verify-package-core.mjs @@ -69,32 +69,3 @@ export const pathExists = async (path) => { throw cause; } }; - -/** Synthetic function dossier for managed/native verification fixtures. */ -export const functionDossier = (name) => { - return { - procedure: { - address: "0x401000", - name, - classification: { - external: false, - thunk: false, - thunk_target: null, - provenance: "synthetic-provider", - }, - signature: null, - locals: [], - }, - pseudocode: "", - assembly: [], - comments: [], - callers: [], - callees: [], - incoming_references: [], - outgoing_references: [], - referenced_strings: [], - referenced_names: [], - basic_blocks: [], - limitations: [], - }; -}; diff --git a/scripts/verify-package-managed.mjs b/scripts/verify-package-managed.mjs index 16ef56993..4f6c9f3f2 100644 --- a/scripts/verify-package-managed.mjs +++ b/scripts/verify-package-managed.mjs @@ -3,7 +3,8 @@ import { join } from "node:path"; import { createEvidence } from "../dist/domain/evidence.js"; import { buildManagedPeFixture } from "./fixtures/managed/pe.mjs"; -import { functionDossier, json, run } from "./lib/verify-package-core.mjs"; +import { functionDossier } from "./fixtures/function-dossier.mjs"; +import { json, run } from "./lib/verify-package-core.mjs"; const buildManagedFixtures = async (workspace) => { const managedPath = join(workspace, "managed-fixture.exe"); diff --git a/scripts/verify/managed/config.mjs b/scripts/verify/managed/config.mjs index f22b15d18..8c9906e32 100644 --- a/scripts/verify/managed/config.mjs +++ b/scripts/verify/managed/config.mjs @@ -50,37 +50,3 @@ export const comparisonLimits = { export const defaultIlBody = Buffer.from([ 0x32, 0x02, 0x7b, 0x01, 0x00, 0x00, 0x04, 0x28, 0x01, 0x00, 0x00, 0x0a, 0x2a, ]); - -export function functionDossier(name) { - return { - procedure: { - address: "0x401000", - name, - classification: { - external: false, - thunk: false, - thunk_target: null, - provenance: "synthetic-provider", - }, - body: { - available: false, - reason: "Synthetic provider does not supply function body ranges.", - }, - signature: null, - locals: [], - }, - pseudocode: "", - assembly: [], - comments: [], - callers: [], - callees: [], - incoming_references: [], - outgoing_references: [], - referenced_strings: [], - referenced_names: [], - basic_blocks: [], - native_api: null, - native_value_flow: null, - limitations: [], - }; -} diff --git a/scripts/verify/managed/conformance.mjs b/scripts/verify/managed/conformance.mjs index 4a0ed5c3b..68d2b090a 100644 --- a/scripts/verify/managed/conformance.mjs +++ b/scripts/verify/managed/conformance.mjs @@ -13,6 +13,7 @@ import { projectManagedApplicationGraphEvidence } from "../../../dist/applicatio import { traceApplicationFeatureEvidence } from "../../../dist/application/javascript/JavaScriptApplicationWorkflowService.js"; import { MANAGED_STATIC_PROVIDER } from "../../../dist/application/InvestigationProviders.js"; import { createEvidence } from "../../../dist/domain/evidence.js"; +import { functionDossier } from "../../fixtures/function-dossier.mjs"; import { alternateMvid, buildNativePeFixture, @@ -21,7 +22,6 @@ import { createManagedConformanceSupport } from "./support.mjs"; import { comparisonLimits, defaultIlBody, - functionDossier, inspectionLimits, memberLimits, nativeBoundaryLimits, diff --git a/tests/fixtures/fakeHopper.mjs b/tests/fixtures/fakeHopper.mjs index a65073b35..392f609c8 100644 --- a/tests/fixtures/fakeHopper.mjs +++ b/tests/fixtures/fakeHopper.mjs @@ -87,6 +87,11 @@ const enhancedFixtureResult = (method) => { procedure: { address: "0x1000", name: "fixture", + classification: null, + body: { + available: false, + reason: "The fixture has no function body-extent observation.", + }, signature: null, locals: [], }, @@ -100,6 +105,9 @@ const enhancedFixtureResult = (method) => { referenced_strings: [], referenced_names: [], basic_blocks: [{ start: "0x1000", end: "0x1001", successors: [] }], + native_api: null, + native_value_flow: null, + limitations: [], }; } case "search_strings": From ac356c46ad6a17c8864bc5d350984786db62d2f5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:58:43 +0800 Subject: [PATCH 081/189] test(javascript): share semantic graph test facts --- .../JavaScriptSemanticGraphBuilder.test.ts | 40 +---------------- .../JavaScriptSemanticGraphResources.test.ts | 41 +----------------- .../JavaScriptSemanticGraphScope.test.ts | 43 +------------------ tests/fixtures/javascriptSemanticGraph.ts | 42 ++++++++++++++++++ 4 files changed, 45 insertions(+), 121 deletions(-) create mode 100644 tests/fixtures/javascriptSemanticGraph.ts diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts index 43d63a7d0..7794debf9 100644 --- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts @@ -1,9 +1,9 @@ import { primitiveByteExpansionSource } from "../../../tests/fixtures/javascriptPrimitiveExpansion.js"; +import { graphForJavaScript as graphFor } from "../../../tests/fixtures/javascriptSemanticGraph.js"; import * as t from "@babel/types"; import { expect, it } from "vitest"; import { - buildJavaScriptSemanticGraph, SEMANTIC_GRAPH_FILE_NODE_CEILING, SEMANTIC_GRAPH_NODE_CEILING, } from "./JavaScriptSemanticGraphBuilder.js"; @@ -12,7 +12,6 @@ import { constructSemanticGraphNode, createSemanticGraphProjectionState, } from "./JavaScriptSemanticGraphConstruction.js"; -import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js"; import { @@ -23,7 +22,6 @@ import { parseJavaScriptSource } from "../../domain/javascript/javascriptSourceP import { semanticCoverageResourceLimits } from "../../domain/javascript/javascriptSemanticCoverage.js"; const SHA256 = "a".repeat(64); -const GRAPH_ID = `jag_${"b".repeat(64)}`; it("projects closure and direct interprocedural flow without execution", () => { const graph = graphFor(` @@ -346,42 +344,6 @@ it("keeps duplicate function fingerprints ambiguous", () => { expect(query.summary.total_seed_matches).toBe(2); }); -const graphFor = (source: string, ir = analyzeJavaScriptSemantics(source)) => { - const file: JavaScriptArtifactFile = { - path: "app.js", - container_sha256: SHA256, - sha256: SHA256, - bytes: Buffer.byteLength(source), - inventory_artifact_id: `art_${SHA256}`, - kind: "javascript", - unpacked: false, - text: { included: true, value: source }, - }; - const analysis: JavaScriptArtifactAnalysis = { - files: [ - { - file, - javascript: null, - semantic: { ir }, - }, - ], - packages: [], - json_modules: [], - html_scripts: [], - source_maps: [], - visited_ast_nodes: 0, - findings: 0, - modules: 0, - parse_failures: 0, - limitations: [], - }; - return buildJavaScriptSemanticGraph({ - rootArtifactSha256: SHA256, - applicationGraph: { graph_id: GRAPH_ID, nodes: [] }, - analysis, - }); -}; - const semanticNodeFor = (roleKey: string) => { const file: JavaScriptArtifactFile = { path: "budget.js", diff --git a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts index afedb6f96..62771c042 100644 --- a/src/application/javascript/JavaScriptSemanticGraphResources.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphResources.test.ts @@ -1,11 +1,10 @@ import { expect, it } from "vitest"; +import { graphForJavaScript as graphFor } from "../../../tests/fixtures/javascriptSemanticGraph.js"; import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js"; import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; -import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js"; import { resolveJavaScriptSemanticEvidence } from "../../domain/javascript/javascriptSemanticGraph.js"; -import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js"; const SHA256 = "a".repeat(64); const GRAPH_ID = `jag_${"b".repeat(64)}`; @@ -359,41 +358,3 @@ const emptyAnalysis = (): JavaScriptArtifactAnalysis => ({ parse_failures: 0, limitations: [], }); - -const graphFor = (source: string) => { - const file: JavaScriptArtifactFile = { - path: "app.js", - container_sha256: SHA256, - sha256: SHA256, - bytes: Buffer.byteLength(source), - inventory_artifact_id: `art_${SHA256}`, - kind: "javascript", - unpacked: false, - text: { included: true, value: source }, - }; - const analysis: JavaScriptArtifactAnalysis = { - files: [ - { - file, - javascript: null, - semantic: { - ir: analyzeJavaScriptSemantics(source), - }, - }, - ], - packages: [], - json_modules: [], - html_scripts: [], - source_maps: [], - visited_ast_nodes: 0, - findings: 0, - modules: 0, - parse_failures: 0, - limitations: [], - }; - return buildJavaScriptSemanticGraph({ - rootArtifactSha256: SHA256, - applicationGraph: { graph_id: GRAPH_ID, nodes: [] }, - analysis, - }); -}; diff --git a/src/application/javascript/JavaScriptSemanticGraphScope.test.ts b/src/application/javascript/JavaScriptSemanticGraphScope.test.ts index fca97b81a..5fc14c68f 100644 --- a/src/application/javascript/JavaScriptSemanticGraphScope.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphScope.test.ts @@ -1,50 +1,9 @@ import { expect, it } from "vitest"; -import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js"; -import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; -import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; +import { graphForJavaScript as graphFor } from "../../../tests/fixtures/javascriptSemanticGraph.js"; import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js"; import { topLevelBinding } from "../../domain/javascript/javascriptSemanticAnalysis.fixture.js"; -const SHA256 = "a".repeat(64); -const GRAPH_ID = `jag_${"b".repeat(64)}`; - -const graphFor = (source: string) => { - const file: JavaScriptArtifactFile = { - path: "app.js", - container_sha256: SHA256, - sha256: SHA256, - bytes: Buffer.byteLength(source), - inventory_artifact_id: `art_${SHA256}`, - kind: "javascript", - unpacked: false, - text: { included: true, value: source }, - }; - const analysis: JavaScriptArtifactAnalysis = { - files: [ - { - file, - javascript: null, - semantic: { ir: analyzeJavaScriptSemantics(source) }, - }, - ], - packages: [], - json_modules: [], - html_scripts: [], - source_maps: [], - visited_ast_nodes: 0, - findings: 0, - modules: 0, - parse_failures: 0, - limitations: [], - }; - return buildJavaScriptSemanticGraph({ - rootArtifactSha256: SHA256, - applicationGraph: { graph_id: GRAPH_ID, nodes: [] }, - analysis, - }); -}; - const dynamicScopeUnknowns = (source: string) => graphFor(source).unknowns.filter(({ reason }) => reason === "dynamic-scope"); diff --git a/tests/fixtures/javascriptSemanticGraph.ts b/tests/fixtures/javascriptSemanticGraph.ts new file mode 100644 index 000000000..0615b5419 --- /dev/null +++ b/tests/fixtures/javascriptSemanticGraph.ts @@ -0,0 +1,42 @@ +import { buildJavaScriptSemanticGraph } from "../../src/application/javascript/JavaScriptSemanticGraphBuilder.js"; +import type { JavaScriptArtifactAnalysis } from "../../src/application/javascript/JavaScriptArtifactAnalysisTypes.js"; +import type { JavaScriptArtifactFile } from "../../src/domain/javascript/javascriptArtifactFiles.js"; +import type { JavaScriptSemanticIr } from "../../src/domain/javascript/javascriptSemanticIr.js"; +import { analyzeJavaScriptSemantics } from "../../src/domain/javascript/javascriptSemanticAnalysis.js"; + +const SHA256 = "a".repeat(64); + +/** Build a semantic graph from one source file for application-level tests. */ +export const graphForJavaScript = ( + source: string, + ir: JavaScriptSemanticIr = analyzeJavaScriptSemantics(source), +) => { + const file: JavaScriptArtifactFile = { + path: "app.js", + container_sha256: SHA256, + sha256: SHA256, + bytes: Buffer.byteLength(source), + inventory_artifact_id: `art_${SHA256}`, + kind: "javascript", + unpacked: false, + text: { included: true, value: source }, + }; + const analysis: JavaScriptArtifactAnalysis = { + files: [{ file, javascript: null, semantic: { ir } }], + packages: [], + json_modules: [], + html_scripts: [], + source_maps: [], + visited_ast_nodes: 0, + findings: 0, + modules: 0, + parse_failures: 0, + limitations: [], + }; + + return buildJavaScriptSemanticGraph({ + rootArtifactSha256: SHA256, + applicationGraph: { graph_id: `jag_${"b".repeat(64)}`, nodes: [] }, + analysis, + }); +}; From 37fcea78cecbeeadd869e9a3d77dd133ed264a0a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:59:42 +0800 Subject: [PATCH 082/189] fix(cli): avoid duplicate primary cleanup diagnostics --- src/application/DirectAnalysisCleanup.ts | 1 - tests/composition/directAnalysisCleanup.test.ts | 8 +++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/application/DirectAnalysisCleanup.ts b/src/application/DirectAnalysisCleanup.ts index 3f3c54425..3f073f7b5 100644 --- a/src/application/DirectAnalysisCleanup.ts +++ b/src/application/DirectAnalysisCleanup.ts @@ -55,7 +55,6 @@ export const directAnalysisCleanupFailure = ( "execution_failure" in primary.data.details ? (primary.data.details.execution_failure ?? primary.data.code) : primary.data.code, - primary_error: projection, cleanup_error: cleanup, }, }; diff --git a/tests/composition/directAnalysisCleanup.test.ts b/tests/composition/directAnalysisCleanup.test.ts index 9e533bb89..22fd84942 100644 --- a/tests/composition/directAnalysisCleanup.test.ts +++ b/tests/composition/directAnalysisCleanup.test.ts @@ -6,6 +6,7 @@ import { } from "../../src/application/DirectAnalysis.js"; import type { DirectAnalysisDependencies } from "../../src/application/DirectAnalysisDependencies.js"; import { parseConfig } from "../../src/config/parseConfig.js"; +import { analysisCliErrorEnvelopeSchema } from "../../src/contracts/errorSchemas.js"; import type { AnalysisError } from "../../src/domain/analysisErrorBase.js"; import { AnalysisTimeoutError } from "../../src/domain/analysisErrorCore.js"; import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js"; @@ -104,7 +105,8 @@ describe("one-shot analysis cleanup outcomes", () => { "read_bytes", {}, ); - expect(result).toMatchObject({ + const callerError = analysisCliErrorEnvelopeSchema.parse(result); + expect(callerError).toMatchObject({ code: "cleanup_incomplete", category: primary.category, message: primary.message, @@ -114,6 +116,10 @@ describe("one-shot analysis cleanup outcomes", () => { cleanup_error: projectAnalysisError(cleanupError), }, }); + expect(callerError.details).not.toHaveProperty("primary_error"); + expect( + JSON.stringify(callerError).match(/retained observation/g), + ).toHaveLength(1); expect(isCliOperationFailure(result)).toBe(true); }); From 5b3715ef825a30150b02d3f1bb7d40dd89453018 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:07:30 +0800 Subject: [PATCH 083/189] docs: correct README setup and runtime guidance --- README.md | 8 ++++---- README_ar.md | 4 ++-- README_de.md | 4 ++-- README_es.md | 4 ++-- README_fa.md | 4 ++-- README_fr.md | 4 ++-- README_ja.md | 4 ++-- README_ko.md | 4 ++-- README_pl.md | 4 ++-- README_pt-BR.md | 4 ++-- README_ru.md | 4 ++-- README_th.md | 4 ++-- README_tr.md | 4 ++-- README_uk.md | 4 ++-- README_vi.md | 4 ++-- README_zh-TW.md | 4 ++-- README_zh.md | 4 ++-- 17 files changed, 36 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 8c25a3ff5..7509d81ea 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#what-you-can-analyze) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -52,7 +52,7 @@ See a feature in an app that you want in your own product? Ask your agent to inv REA connects your agent to tools for inspecting native binaries, JavaScript and Electron apps, .NET assemblies, and websites. You can also use the same tools from your terminal. Analysis runs locally, and results include the evidence and limitations behind each conclusion. -Setup registers REA with your agent and installs matching workflow instructions. Native analysis can use an existing Hopper or Ghidra installation; setup can optionally install Hopper with approval. Static JavaScript analysis needs neither engine. +Setup registers REA with your agent and installs matching workflow instructions. Native analysis can use an existing Hopper, Ghidra, or IDA installation; setup can optionally install Hopper with approval. Static JavaScript analysis needs no native analysis engine. > **[Visit the REA website](https://rea.tools/)** for setup instructions, illustrated guides, and real case studies. @@ -156,7 +156,7 @@ Additional tools and host support depend on the target: | JavaScript / Electron | Modules, imports, source maps, routes, IPC and native add-on relationships | Node.js and npm; [application analysis](https://rea.tools/guides/javascript/) | | Websites | Page structure, scripts, network observations and requested screenshots | A Chrome-family browser; [browser analysis](https://rea.tools/guides/browser/) | | Saved network captures | Requests, responses, exposed payloads and source locations | HAR; mitmdump on Linux for native mitmproxy captures; [capture guide](docs/web-network-captures.md) | -| .NET assemblies | Metadata, CIL instructions, declared native dependencies and build comparisons | Static inspection; [managed-code guide](docs/managed-code-analysis.md) | +| .NET assemblies | Metadata, CIL instructions, declared native dependencies and build comparisons | None (static only); [managed-code guide](docs/managed-code-analysis.md) | | Android APKs | Manifest declarations, classes, decompiled methods and references | Headless JADX and a full JDK on Linux/macOS/Windows x64; [Android guide](docs/android-analysis.md) | | Firmware | Regions, extraction results and native-analysis handoffs | Binwalk / Unblob on Linux; [firmware guide](docs/firmware-analysis.md) | | Packages and resources | File inventories, digests, plists, Apple bundle anatomy and extracted resources | [Artifact and JavaScript guide](docs/javascript-artifact-reconstruction.md), [Apple applications](docs/apple-application-analysis.md) | @@ -245,7 +245,7 @@ ask you to choose demo mode or activate your license. See
What does installing the skill from skills.sh do? -The skill supplies investigation instructions for your agent. Use `rea setup` +The skill supplies investigation instructions for your agent. Use `npx rea-agents setup` to register REA's MCP server and install the matching instructions, then restart your agent. See [skill-only installation](docs/installation.md#skill-only-installation). diff --git a/README_ar.md b/README_ar.md index c2421439b..92151b9c7 100644 --- a/README_ar.md +++ b/README_ar.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -204,7 +204,7 @@ npx rea-agents@latest setup
ماذا يفعل تثبيت المهارة من skills.sh؟ -توفّر المهارة تعليمات الاستقصاء لوكيلك. استخدم `rea setup` لتسجيل خادم MCP الخاص بـ REA وتثبيت التعليمات المطابقة، ثم أعد تشغيل وكيلك. راجع [تثبيت المهارة وحدها](docs/installation.md#skill-only-installation). +توفّر المهارة تعليمات الاستقصاء لوكيلك. استخدم `npx rea-agents setup` لتسجيل خادم MCP الخاص بـ REA وتثبيت التعليمات المطابقة، ثم أعد تشغيل وكيلك. راجع [تثبيت المهارة وحدها](docs/installation.md#skill-only-installation).
diff --git a/README_de.md b/README_de.md index de83b78a5..b71795bc0 100644 --- a/README_de.md +++ b/README_de.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA startet Hopper, wenn eine Operation es benötigt. Unter macOS kann beim erst
Was bewirkt die Installation des Skills über skills.sh? -Der Skill stellt Untersuchungsanweisungen für deinen Agenten bereit. Verwende `rea setup`, um den MCP-Server von REA zu registrieren und passende Anweisungen zu installieren. Starte deinen Agenten anschließend neu. Siehe [Installation nur des Skills](docs/installation.md#skill-only-installation). +Der Skill stellt Untersuchungsanweisungen für deinen Agenten bereit. Verwende `npx rea-agents setup`, um den MCP-Server von REA zu registrieren und passende Anweisungen zu installieren. Starte deinen Agenten anschließend neu. Siehe [Installation nur des Skills](docs/installation.md#skill-only-installation).
diff --git a/README_es.md b/README_es.md index 54cbcbf0d..ac86b1f4d 100644 --- a/README_es.md +++ b/README_es.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA inicia Hopper cuando una operación lo necesita. En macOS, puede aparecer un
¿Qué hace la instalación de la skill desde skills.sh? -La skill proporciona instrucciones de investigación a tu agente. Usa `rea setup` para registrar el servidor MCP de REA e instalar las instrucciones correspondientes; después reinicia tu agente. Consulta [instalación solo de la skill](docs/installation.md#skill-only-installation). +La skill proporciona instrucciones de investigación a tu agente. Usa `npx rea-agents setup` para registrar el servidor MCP de REA e instalar las instrucciones correspondientes; después reinicia tu agente. Consulta [instalación solo de la skill](docs/installation.md#skill-only-installation).
diff --git a/README_fa.md b/README_fa.md index 1fe6e6df6..7b2b307d9 100644 --- a/README_fa.md +++ b/README_fa.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -190,7 +190,7 @@ REA زمانی که عملیاتی به Hopper نیاز داشته باشد آن
نصب skill از skills.sh چه کاری انجام می‌دهد؟ -این skill دستورالعمل‌های بررسی را برای ایجنت فراهم می‌کند. برای ثبت سرور MCP مربوط به REA و نصب دستورالعمل‌های متناظر، `rea setup` را اجرا کنید و سپس ایجنت را مجدداً راه‌اندازی کنید. [نصب مستقل skill](docs/installation.md#skill-only-installation) را ببینید. +این skill دستورالعمل‌های بررسی را برای ایجنت فراهم می‌کند. برای ثبت سرور MCP مربوط به REA و نصب دستورالعمل‌های متناظر، `npx rea-agents setup` را اجرا کنید و سپس ایجنت را مجدداً راه‌اندازی کنید. [نصب مستقل skill](docs/installation.md#skill-only-installation) را ببینید.
diff --git a/README_fr.md b/README_fr.md index d61d3198c..8fa07803b 100644 --- a/README_fr.md +++ b/README_fr.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -203,7 +203,7 @@ REA lance Hopper lorsqu'une opération en a besoin. Sous macOS, une boîte de di
Que fait l'installation du skill depuis skills.sh ? -Le skill fournit des instructions d'investigation à votre agent. Utilisez `rea setup` pour enregistrer le serveur MCP de REA et installer les instructions correspondantes, puis redémarrez votre agent. Consultez [l'installation du skill seul](docs/installation.md#skill-only-installation). +Le skill fournit des instructions d'investigation à votre agent. Utilisez `npx rea-agents setup` pour enregistrer le serveur MCP de REA et installer les instructions correspondantes, puis redémarrez votre agent. Consultez [l'installation du skill seul](docs/installation.md#skill-only-installation).
diff --git a/README_ja.md b/README_ja.md index ba30700f6..b827c3c04 100644 --- a/README_ja.md +++ b/README_ja.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -204,7 +204,7 @@ REA は必要な操作の際に Hopper を起動します。macOS では、初
skills.sh からスキルをインストールすると何ができますか? -スキルはエージェントに調査の手順を提供します。`rea setup` で REA の MCP サーバーを登録し、対応する手順をインストールしてから、エージェントを再起動してください。[スキルのみのインストール](docs/installation.md#skill-only-installation)を参照してください。 +スキルはエージェントに調査の手順を提供します。`npx rea-agents setup` で REA の MCP サーバーを登録し、対応する手順をインストールしてから、エージェントを再起動してください。[スキルのみのインストール](docs/installation.md#skill-only-installation)を参照してください。
diff --git a/README_ko.md b/README_ko.md index 7e53fe5fd..876792059 100644 --- a/README_ko.md +++ b/README_ko.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -204,7 +204,7 @@ REA는 작업에 필요할 때 Hopper를 실행합니다. macOS에서는 처음
skills.sh에서 설치하는 스킬은 어떤 역할을 하나요? -스킬은 에이전트에게 조사 지침을 제공합니다. `rea setup`으로 REA의 MCP 서버를 등록하고 버전에 맞는 지침을 설치한 뒤 에이전트를 다시 시작하세요. [스킬만 설치하기](docs/installation.md#skill-only-installation)를 참고하세요. +스킬은 에이전트에게 조사 지침을 제공합니다. `npx rea-agents setup`으로 REA의 MCP 서버를 등록하고 버전에 맞는 지침을 설치한 뒤 에이전트를 다시 시작하세요. [스킬만 설치하기](docs/installation.md#skill-only-installation)를 참고하세요.
diff --git a/README_pl.md b/README_pl.md index b80f04918..bdd062da9 100644 --- a/README_pl.md +++ b/README_pl.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA uruchamia Hoppera, gdy wymaga tego operacja. W systemie macOS przy pierwszym
Co daje zainstalowanie umiejętności z skills.sh? -Umiejętność dostarcza agentowi instrukcje prowadzenia analizy. Użyj `rea setup`, aby zarejestrować serwer MCP REA i zainstalować pasujące instrukcje, a następnie uruchom agenta ponownie. Zobacz [instalację samej umiejętności](docs/installation.md#skill-only-installation). +Umiejętność dostarcza agentowi instrukcje prowadzenia analizy. Użyj `npx rea-agents setup`, aby zarejestrować serwer MCP REA i zainstalować pasujące instrukcje, a następnie uruchom agenta ponownie. Zobacz [instalację samej umiejętności](docs/installation.md#skill-only-installation).
diff --git a/README_pt-BR.md b/README_pt-BR.md index 89b1820a5..711f7d788 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ O REA inicia o Hopper quando uma operação precisa dele. No macOS, um diálogo
O que faz a instalação da skill pelo skills.sh? -A skill fornece instruções de investigação ao seu agente. Use `rea setup` para registrar o servidor MCP do REA e instalar as instruções correspondentes, depois reinicie seu agente. Consulte [instalação apenas da skill](docs/installation.md#skill-only-installation). +A skill fornece instruções de investigação ao seu agente. Use `npx rea-agents setup` para registrar o servidor MCP do REA e instalar as instruções correspondentes, depois reinicie seu agente. Consulte [instalação apenas da skill](docs/installation.md#skill-only-installation).
diff --git a/README_ru.md b/README_ru.md index 6dc2815f7..6b44940e9 100644 --- a/README_ru.md +++ b/README_ru.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA запускает Hopper, когда он нужен для операци
Что даёт установка skill с skills.sh? -Skill предоставляет агенту инструкции по исследованию. Используйте `rea setup`, чтобы зарегистрировать MCP-сервер REA и установить соответствующие инструкции, затем перезапустите агента. См. [установку только skill](docs/installation.md#skill-only-installation). +Skill предоставляет агенту инструкции по исследованию. Используйте `npx rea-agents setup`, чтобы зарегистрировать MCP-сервер REA и установить соответствующие инструкции, затем перезапустите агента. См. [установку только skill](docs/installation.md#skill-only-installation).
diff --git a/README_th.md b/README_th.md index d23d4998b..c66e1a393 100644 --- a/README_th.md +++ b/README_th.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA เริ่ม Hopper เมื่อการดำเนินการ
การติดตั้งสกิลจาก skills.sh ทำอะไร? -สกิลให้คำแนะนำการตรวจสอบแก่เอเจนต์ ใช้ `rea setup` เพื่อลงทะเบียนเซิร์ฟเวอร์ MCP ของ REA และติดตั้งคำแนะนำที่ตรงกัน แล้วเริ่มเอเจนต์ใหม่ ดู[การติดตั้งเฉพาะสกิล](docs/installation.md#skill-only-installation) +สกิลให้คำแนะนำการตรวจสอบแก่เอเจนต์ ใช้ `npx rea-agents setup` เพื่อลงทะเบียนเซิร์ฟเวอร์ MCP ของ REA และติดตั้งคำแนะนำที่ตรงกัน แล้วเริ่มเอเจนต์ใหม่ ดู[การติดตั้งเฉพาะสกิล](docs/installation.md#skill-only-installation)
diff --git a/README_tr.md b/README_tr.md index 43d502a2b..ff5ae3239 100644 --- a/README_tr.md +++ b/README_tr.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA, bir işlem gerektirdiğinde Hopper'ı başlatır. macOS'ta ilk çalıştır
skills.sh üzerinden skill yüklemek ne yapar? -Skill, ajanınıza araştırma talimatları sağlar. REA'nın MCP sunucusunu kaydetmek ve uyumlu talimatları yüklemek için `rea setup` kullanın, ardından ajanınızı yeniden başlatın. [Yalnızca skill yükleme](docs/installation.md#skill-only-installation) belgesine bakın. +Skill, ajanınıza araştırma talimatları sağlar. REA'nın MCP sunucusunu kaydetmek ve uyumlu talimatları yüklemek için `npx rea-agents setup` kullanın, ardından ajanınızı yeniden başlatın. [Yalnızca skill yükleme](docs/installation.md#skill-only-installation) belgesine bakın.
diff --git a/README_uk.md b/README_uk.md index 1a6352867..973ff9b41 100644 --- a/README_uk.md +++ b/README_uk.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA запускає Hopper, коли він потрібен для опера
Що дає встановлення skill із skills.sh? -Skill надає агенту інструкції дослідження. Використовуйте `rea setup`, щоб зареєструвати MCP-сервер REA та встановити відповідні інструкції, а потім перезапустіть агента. Дивіться [встановлення лише skill](docs/installation.md#skill-only-installation). +Skill надає агенту інструкції дослідження. Використовуйте `npx rea-agents setup`, щоб зареєструвати MCP-сервер REA та встановити відповідні інструкції, а потім перезапустіть агента. Дивіться [встановлення лише skill](docs/installation.md#skill-only-installation).
diff --git a/README_vi.md b/README_vi.md index a3d492724..6f198f90f 100644 --- a/README_vi.md +++ b/README_vi.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -202,7 +202,7 @@ REA khởi chạy Hopper khi một thao tác cần đến nó. Trên macOS, hộ
Cài skill từ skills.sh có tác dụng gì? -Skill cung cấp hướng dẫn điều tra cho tác nhân. Dùng `rea setup` để đăng ký máy chủ MCP của REA và cài hướng dẫn tương ứng, sau đó khởi động lại tác nhân. Xem [chỉ cài skill](docs/installation.md#skill-only-installation). +Skill cung cấp hướng dẫn điều tra cho tác nhân. Dùng `npx rea-agents setup` để đăng ký máy chủ MCP của REA và cài hướng dẫn tương ứng, sau đó khởi động lại tác nhân. Xem [chỉ cài skill](docs/installation.md#skill-only-installation).
diff --git a/README_zh-TW.md b/README_zh-TW.md index 8317d1c36..adef7444c 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -204,7 +204,7 @@ REA 會在操作需要時啟動 Hopper。在 macOS 上,首次執行時可能
從 skills.sh 安裝 skill 有什麼作用? -skill 為 AI 代理提供調查指引。使用 `rea setup` 註冊 REA 的 MCP 服務並安裝對應的指引,然後重新啟動 AI 代理。見[僅安裝 skill](docs/installation.md#skill-only-installation)。 +skill 為 AI 代理提供調查指引。使用 `npx rea-agents setup` 註冊 REA 的 MCP 服務並安裝對應的指引,然後重新啟動 AI 代理。見[僅安裝 skill](docs/installation.md#skill-only-installation)。
diff --git a/README_zh.md b/README_zh.md index 710773ad3..baf67a145 100644 --- a/README_zh.md +++ b/README_zh.md @@ -11,7 +11,7 @@ [![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents) [![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml) [![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog) -[![Node.js 22+](https://img.shields.io/badge/Node.js-22.19%2B-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/) +[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status) [![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything) [![MIT license](https://img.shields.io/badge/license-MIT-f4c430?style=flat-square)](LICENSE) [![Discord](https://img.shields.io/discord/1556595354999332884?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/GkcryMnJDM) @@ -204,7 +204,7 @@ REA 会在操作需要时启动 Hopper。在 macOS 上,首次运行时可能
从 skills.sh 安装 skill 有什么作用? -skill 为智能体提供调查指引。使用 `rea setup` 注册 REA 的 MCP 服务并安装匹配的指引,然后重启智能体。见[仅安装 skill](docs/installation.md#skill-only-installation)。 +skill 为智能体提供调查指引。使用 `npx rea-agents setup` 注册 REA 的 MCP 服务并安装匹配的指引,然后重启智能体。见[仅安装 skill](docs/installation.md#skill-only-installation)。
From 66a20a2597b5daebc0a292361aa62a78b7df6e7d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:09:23 +0800 Subject: [PATCH 084/189] test(managed): include shared dossier fixture in artifact inputs --- scripts/fixtures/{ => managed}/function-dossier.mjs | 2 +- scripts/verify-package-managed.mjs | 2 +- scripts/verify/managed/conformance.mjs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename scripts/fixtures/{ => managed}/function-dossier.mjs (91%) diff --git a/scripts/fixtures/function-dossier.mjs b/scripts/fixtures/managed/function-dossier.mjs similarity index 91% rename from scripts/fixtures/function-dossier.mjs rename to scripts/fixtures/managed/function-dossier.mjs index c1b0cd0f5..125d41e62 100644 --- a/scripts/fixtures/function-dossier.mjs +++ b/scripts/fixtures/managed/function-dossier.mjs @@ -1,4 +1,4 @@ -import { functionDossierSchema } from "../../dist/domain/hopperValues.js"; +import { functionDossierSchema } from "../../../dist/domain/hopperValues.js"; /** Validated synthetic native observations shared by managed verification lanes. */ export const functionDossier = (name) => diff --git a/scripts/verify-package-managed.mjs b/scripts/verify-package-managed.mjs index 4f6c9f3f2..87b81bf6f 100644 --- a/scripts/verify-package-managed.mjs +++ b/scripts/verify-package-managed.mjs @@ -3,7 +3,7 @@ import { join } from "node:path"; import { createEvidence } from "../dist/domain/evidence.js"; import { buildManagedPeFixture } from "./fixtures/managed/pe.mjs"; -import { functionDossier } from "./fixtures/function-dossier.mjs"; +import { functionDossier } from "./fixtures/managed/function-dossier.mjs"; import { json, run } from "./lib/verify-package-core.mjs"; const buildManagedFixtures = async (workspace) => { diff --git a/scripts/verify/managed/conformance.mjs b/scripts/verify/managed/conformance.mjs index 68d2b090a..3dbf56742 100644 --- a/scripts/verify/managed/conformance.mjs +++ b/scripts/verify/managed/conformance.mjs @@ -13,7 +13,7 @@ import { projectManagedApplicationGraphEvidence } from "../../../dist/applicatio import { traceApplicationFeatureEvidence } from "../../../dist/application/javascript/JavaScriptApplicationWorkflowService.js"; import { MANAGED_STATIC_PROVIDER } from "../../../dist/application/InvestigationProviders.js"; import { createEvidence } from "../../../dist/domain/evidence.js"; -import { functionDossier } from "../../fixtures/function-dossier.mjs"; +import { functionDossier } from "../../fixtures/managed/function-dossier.mjs"; import { alternateMvid, buildNativePeFixture, From 7829b1aeef8f43f186be2d2adbd6c67541306a7a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:14:28 +0800 Subject: [PATCH 085/189] fix(filesystem): reject unstable artifact targets --- src/application/BinaryTargetResolver.ts | 39 +++++++-- src/application/RegularFileRead.ts | 30 +------ src/application/WebScriptExportService.ts | 3 +- src/artifacts/inventory/classify.ts | 83 +++++++++++++++++-- .../inventory/hashStableRootArtifact.ts | 67 +++++++++++++++ src/artifacts/inventory/scanCanonical.ts | 18 ++-- src/cliJsonInput.ts | 6 +- src/filesystem/RegularFile.ts | 58 +++++++++++++ .../artifactInventoryRegularRoot.test.ts | 42 ++++++++++ .../boundary/filesystem/binaryTarget.test.ts | 23 +++++ tests/boundary/mcp/openBinaryFifo.test.ts | 48 +++++++++++ 11 files changed, 359 insertions(+), 58 deletions(-) create mode 100644 src/artifacts/inventory/hashStableRootArtifact.ts create mode 100644 src/filesystem/RegularFile.ts create mode 100644 tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts create mode 100644 tests/boundary/mcp/openBinaryFifo.test.ts diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index f45a1d9a6..c1ec900bd 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -2,7 +2,7 @@ import { constants } from "node:fs"; import { createHash } from "node:crypto"; import { access, - open, + lstat, realpath, stat, type FileHandle, @@ -10,6 +10,10 @@ import { import { extname, isAbsolute, resolve } from "node:path"; import { BinaryTargetError } from "../domain/configurationErrors.js"; +import { + openRegularFile, + sameRegularFileState, +} from "../filesystem/RegularFile.js"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -69,11 +73,13 @@ export const parseBinaryTarget = async ( const { executable: path, infoPlist } = resolved.value; const bundle = infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist }; - const handle = await open(path, "r"); + const handle = await openRegularFile(path, { + symlinks: "reject", + signal, + }); try { throwIfTargetResolutionCancelled(signal); - if (!(await handle.stat()).isFile()) - return err(new BinaryTargetError(path, "target is not a regular file")); + const metadata = await handle.stat(); throwIfTargetResolutionCancelled(signal); if (formatHint === "dos-com") { if (targetKind !== undefined && targetKind !== "executable") @@ -83,12 +89,12 @@ export const parseBinaryTarget = async ( "DOS COM format requires an executable target kind", ), ); - const length = validateDosComLength((await handle.stat()).size); + const length = validateDosComLength(metadata.size); if (!length.ok) return err(new BinaryTargetError(path, length.error)); return ok({ path, sourcePath: canonical, - sha256: await sha256Handle(handle, signal), + sha256: await sha256Handle(handle, path, metadata, signal), kind: "executable", format: "dos-com", architecture: "x86", @@ -102,7 +108,7 @@ export const parseBinaryTarget = async ( return ok({ path, sourcePath: process.platform === "win32" ? candidate : canonical, - sha256: await sha256Handle(handle, signal), + sha256: await sha256Handle(handle, path, metadata, signal), kind: "database", format: "analysis-database", }); @@ -111,7 +117,7 @@ export const parseBinaryTarget = async ( const identity = { path, sourcePath: process.platform === "win32" ? candidate : canonical, - sha256: await sha256Handle(handle, signal), + sha256: await sha256Handle(handle, path, metadata, signal), }; return isArchiveFormat(artifactFormat) ? ok({ ...identity, kind: "archive", format: artifactFormat }) @@ -127,7 +133,7 @@ export const parseBinaryTarget = async ( path, sourcePath: process.platform === "win32" ? candidate : canonical, ...bundle, - sha256: await sha256Handle(handle, signal), + sha256: await sha256Handle(handle, path, metadata, signal), kind: "executable", ...detected.value, }); @@ -136,6 +142,7 @@ export const parseBinaryTarget = async ( } } catch (cause: unknown) { if (cause instanceof AnalysisCancelledError) return err(cause); + if (cause instanceof BinaryTargetError) return err(cause); if (!(cause instanceof Error)) throw cause; const code = filesystemErrorCode(cause); if (code === undefined) throw cause; @@ -164,6 +171,10 @@ const targetFailureReason = (code: string, detail: string): string => { return `permission denied while reading target: ${detail}`; case "EISDIR": return `target is a directory, not a readable file: ${detail}`; + case "ENOTFILE": + return "target is not a regular file"; + case "ELOOP": + return `target changed while being opened: ${detail}`; default: return `target could not be read (${code}): ${detail}`; } @@ -235,6 +246,8 @@ const isArchiveFormat = ( const sha256Handle = async ( handle: FileHandle, + path: string, + initial: Awaited>, signal?: AbortSignal, ): Promise => { const hash = createHash("sha256"); @@ -248,6 +261,14 @@ const sha256Handle = async ( hash.update(chunk.subarray(0, observed.bytesRead)); position += observed.bytesRead; } + throwIfTargetResolutionCancelled(signal); + const [opened, currentPath] = await Promise.all([handle.stat(), lstat(path)]); + if ( + !sameRegularFileState(initial, opened) || + !sameRegularFileState(initial, currentPath) || + position !== initial.size + ) + throw new BinaryTargetError(path, "target changed while being read"); return hash.digest("hex"); }; diff --git a/src/application/RegularFileRead.ts b/src/application/RegularFileRead.ts index c5ad5f9e3..486e8c54d 100644 --- a/src/application/RegularFileRead.ts +++ b/src/application/RegularFileRead.ts @@ -1,38 +1,12 @@ -import { constants } from "node:fs"; -import { open } from "node:fs/promises"; - -/** The opened input cannot supply regular-file bytes. */ -export class NonRegularFileReadError extends Error { - readonly code: "EISDIR" | "ENOTFILE"; - - constructor( - readonly path: string, - directory: boolean, - ) { - super(`Selected input must be a regular file: ${path}`); - this.name = "NonRegularFileReadError"; - this.code = directory ? "EISDIR" : "ENOTFILE"; - } -} +import { openRegularFile } from "../filesystem/RegularFile.js"; /** Admit a regular file without waiting for a pipe, then read its verified handle. */ export const readRegularFile = async ( path: string, signal?: AbortSignal, ): Promise => { - signal?.throwIfAborted(); - const handle = await open( - path, - constants.O_RDONLY | - (constants.O_NONBLOCK ?? 0) | - (constants.O_NOCTTY ?? 0), - ); + const handle = await openRegularFile(path, { symlinks: "follow", signal }); try { - signal?.throwIfAborted(); - const stats = await handle.stat(); - signal?.throwIfAborted(); - if (!stats.isFile()) - throw new NonRegularFileReadError(path, stats.isDirectory()); const bytes = await handle.readFile({ signal }); signal?.throwIfAborted(); return bytes; diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index dfe54bb8e..1b3a47b7e 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -26,7 +26,8 @@ import { import { WebScriptExportError } from "../domain/webScriptExportError.js"; import type { ExecutionOptions } from "./AnalysisProvider.js"; import { WEB_SCRIPT_EXPORT_PROVIDER as PROVIDER } from "./InvestigationProviders.js"; -import { NonRegularFileReadError, readRegularFile } from "./RegularFileRead.js"; +import { readRegularFile } from "./RegularFileRead.js"; +import { NonRegularFileReadError } from "../filesystem/RegularFile.js"; const OPERATION = "export_web_scripts"; diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index 1cd6c754d..a8baf7a12 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -1,4 +1,10 @@ -import { open } from "node:fs/promises"; +import { + NonRegularFileReadError, + openRegularFile, + sameRegularFileState, +} from "../../filesystem/RegularFile.js"; +import type { FileHandle } from "node:fs/promises"; +import type { Stats } from "node:fs"; import { classifyArtifactContent } from "./ArtifactGraphConstruction.js"; import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js"; @@ -7,6 +13,9 @@ import { hasZipSignature, zipPackageFormatForPath, } from "../../domain/zipPackageFormat.js"; +import { ArtifactReaderFailure } from "../ArtifactReader.js"; +import type { HashResult } from "../ArtifactHash.js"; +import { hashStableRootArtifactHandle } from "./hashStableRootArtifact.js"; const classifyContainerExtension = ( path: string, @@ -26,15 +35,73 @@ export const classifyRoot = async ( if (directory) return "directory"; const extensionFormat = classifyContainerExtension(path); if (extensionFormat !== undefined) return extensionFormat; - const handle = await open(path, "r"); + const handle = await openRootFile(path); try { - const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES); - const observed = await handle.read(magic, 0, magic.length, 0); - const prefix = magic.subarray(0, observed.bytesRead); - if (hasZipSignature(prefix)) return "zip"; - return classifyArtifactContent(path, prefix, (await handle.stat()).size) - .format; + return await classifyOpenedRoot(path, handle); } finally { await handle.close(); } }; + +/** Classify and hash one file root through the same stable open descriptor. */ +export const classifyAndHashRoot = async ( + path: string, + directory: boolean, + expectedMetadata: Stats, + signal?: AbortSignal, +): Promise<{ + readonly format: ArtifactOccurrence["artifact_format"]; + readonly digest: HashResult | null; +}> => { + if (directory) return { format: "directory", digest: null }; + const handle = await openRootFile(path, signal); + try { + const initial = await handle.stat(); + if (!sameRegularFileState(expectedMetadata, initial)) + throw new ArtifactReaderFailure( + "integrity", + `Root artifact changed before inventory: ${path}`, + ); + const format = + classifyContainerExtension(path) ?? + (await classifyOpenedRoot(path, handle)); + const digest = await hashStableRootArtifactHandle( + path, + handle, + initial, + signal, + ); + return { format, digest }; + } finally { + await handle.close(); + } +}; + +const openRootFile = async ( + path: string, + signal?: AbortSignal, +): Promise => { + try { + return await openRegularFile(path, { symlinks: "reject", signal }); + } catch (cause: unknown) { + if (cause instanceof NonRegularFileReadError) + throw new ArtifactReaderFailure( + "format", + `Artifact root is not a regular file: ${path}`, + { cause }, + ); + throw cause; + } +}; + +const classifyOpenedRoot = async ( + path: string, + handle: FileHandle, +): Promise => { + const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES); + const observed = await handle.read(magic, 0, magic.length, 0); + const prefix = magic.subarray(0, observed.bytesRead); + if (hasZipSignature(prefix)) return "zip"; + return classifyArtifactContent(path, prefix, (await handle.stat()).size) + .format; +}; diff --git a/src/artifacts/inventory/hashStableRootArtifact.ts b/src/artifacts/inventory/hashStableRootArtifact.ts new file mode 100644 index 000000000..e441062d3 --- /dev/null +++ b/src/artifacts/inventory/hashStableRootArtifact.ts @@ -0,0 +1,67 @@ +import { lstat } from "node:fs/promises"; +import type { FileHandle } from "node:fs/promises"; + +import { ArtifactReaderFailure } from "../ArtifactReader.js"; +import { + NonRegularFileReadError, + openRegularFile, + sameRegularFileState, +} from "../../filesystem/RegularFile.js"; +import { + abortIfNeeded, + hashReadable, + type HashResult, +} from "../ArtifactHash.js"; + +/** Hash one stable regular root file from the same descriptor that was checked. */ +export const hashStableRootArtifact = async ( + path: string, + signal?: AbortSignal, +): Promise => { + let handle: FileHandle; + try { + handle = await openRegularFile(path, { + symlinks: "reject", + signal, + }); + } catch (cause: unknown) { + if (cause instanceof NonRegularFileReadError) + throw new ArtifactReaderFailure( + "format", + `Artifact root is not a regular file: ${path}`, + { cause }, + ); + throw cause; + } + try { + const initial = await handle.stat(); + return await hashStableRootArtifactHandle(path, handle, initial, signal); + } finally { + await handle.close(); + } +}; + +/** Hash and revalidate the same open descriptor used for root classification. */ +export const hashStableRootArtifactHandle = async ( + path: string, + handle: FileHandle, + initial: Awaited>, + signal?: AbortSignal, +): Promise => { + const digest = await hashReadable( + handle.createReadStream({ autoClose: false }), + signal, + ); + abortIfNeeded(signal); + const [opened, currentPath] = await Promise.all([handle.stat(), lstat(path)]); + if ( + !sameRegularFileState(initial, opened) || + !sameRegularFileState(initial, currentPath) || + digest.bytes !== initial.size + ) + throw new ArtifactReaderFailure( + "integrity", + `Root artifact changed during inventory: ${path}`, + ); + return digest; +}; diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index da046f18b..ca1324e17 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -1,7 +1,6 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; -import { createReadStream } from "node:fs"; import { lstat } from "node:fs/promises"; import type { Stats } from "node:fs"; @@ -30,8 +29,9 @@ import { artifactGraphDigest, artifactManifestId, } from "../../domain/artifactIdentity.js"; -import { classifyRoot } from "./classify.js"; -import { hashReadable, type HashResult } from "../ArtifactHash.js"; +import { classifyAndHashRoot } from "./classify.js"; +import { type HashResult } from "../ArtifactHash.js"; +import { hashStableRootArtifact } from "./hashStableRootArtifact.js"; import { createReader, inventoryLimitations } from "./reader.js"; import { scanReader, @@ -49,10 +49,12 @@ export const scanCanonicalArtifactInventory = async ( ): Promise => { const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY; const metadata = await lstat(path); - const rootFormat = await classifyRoot(path, metadata.isDirectory()); - const rootDigest = metadata.isDirectory() - ? null - : await hashReadable(createReadStream(path), options.signal); + const { format: rootFormat, digest: rootDigest } = await classifyAndHashRoot( + path, + metadata.isDirectory(), + metadata, + options.signal, + ); const reader = await readerFactory( path, rootFormat, @@ -240,7 +242,7 @@ const verifyRootDigest = async ( signal: AbortSignal | undefined, ): Promise => { if (rootDigest === null) return; - const verified = await hashReadable(createReadStream(path), signal); + const verified = await hashStableRootArtifact(path, signal); if ( verified.sha256 !== rootDigest.sha256 || verified.bytes !== rootDigest.bytes diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts index 6b3947ffc..ebab099fe 100644 --- a/src/cliJsonInput.ts +++ b/src/cliJsonInput.ts @@ -1,10 +1,8 @@ import { constants as bufferConstants } from "node:buffer"; import { resolve } from "node:path"; -import { - NonRegularFileReadError, - readRegularFile, -} from "./application/RegularFileRead.js"; +import { readRegularFile } from "./application/RegularFileRead.js"; +import { NonRegularFileReadError } from "./filesystem/RegularFile.js"; import { parseUtf8Json } from "./application/Utf8JsonInput.js"; import { AnalysisAccessDeniedError, diff --git a/src/filesystem/RegularFile.ts b/src/filesystem/RegularFile.ts new file mode 100644 index 000000000..e5afac401 --- /dev/null +++ b/src/filesystem/RegularFile.ts @@ -0,0 +1,58 @@ +import { constants } from "node:fs"; +import type { BigIntStats, Stats } from "node:fs"; +import { open, type FileHandle } from "node:fs/promises"; + +export class NonRegularFileReadError extends Error { + readonly code: "EISDIR" | "ENOTFILE"; + + constructor( + readonly path: string, + directory: boolean, + ) { + super(`Selected input must be a regular file: ${path}`); + this.name = "NonRegularFileReadError"; + this.code = directory ? "EISDIR" : "ENOTFILE"; + } +} + +/** Open and verify the selected file descriptor without blocking on pipes. */ +export const openRegularFile = async ( + path: string, + options: { + readonly symlinks: "follow" | "reject"; + readonly signal?: AbortSignal | undefined; + }, +): Promise => { + options.signal?.throwIfAborted(); + const handle = await open( + path, + constants.O_RDONLY | + (constants.O_NONBLOCK ?? 0) | + (constants.O_NOCTTY ?? 0) | + (options.symlinks === "reject" ? (constants.O_NOFOLLOW ?? 0) : 0), + ); + try { + options.signal?.throwIfAborted(); + const metadata = await handle.stat(); + options.signal?.throwIfAborted(); + if (!metadata.isFile()) + throw new NonRegularFileReadError(path, metadata.isDirectory()); + return handle; + } catch (cause: unknown) { + await handle.close().catch(() => undefined); + throw cause; + } +}; + +/** Compare one regular file's identity and mutable metadata across a read. */ +export const sameRegularFileState = ( + expected: Stats | BigIntStats, + observed: Stats | BigIntStats, +): boolean => + observed.isFile() && + expected.dev === observed.dev && + expected.ino === observed.ino && + expected.size === observed.size && + expected.mode === observed.mode && + expected.mtimeMs === observed.mtimeMs && + expected.ctimeMs === observed.ctimeMs; diff --git a/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts new file mode 100644 index 000000000..b2e4f6d78 --- /dev/null +++ b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts @@ -0,0 +1,42 @@ +import { execFile } from "node:child_process"; +import { lstat, rename, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +import { expect, it } from "vitest"; + +import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js"; +import { classifyAndHashRoot } from "../../../src/artifacts/inventory/classify.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +it.skipIf(process.platform === "win32")( + "rejects a FIFO artifact root without waiting for a writer", + async () => { + const root = await createTestTempDirectory("rea-artifact-root-fifo-"); + const fifoPath = join(root, "input.asar"); + await promisify(execFile)("mkfifo", [fifoPath]); + + await expect(inventoryArtifact(fifoPath)).rejects.toMatchObject({ + reason: "format", + message: `Artifact root is not a regular file: ${fifoPath}`, + }); + }, +); + +it("rejects a root path replaced between its initial stat and open", async () => { + const root = await createTestTempDirectory("rea-artifact-root-replaced-"); + const path = join(root, "input.bin"); + const replacement = join(root, "replacement.bin"); + await writeFile(path, "first bytes\n"); + const expectedMetadata = await lstat(path); + await writeFile(replacement, "different bytes\n"); + await rm(path); + await rename(replacement, path); + + await expect( + classifyAndHashRoot(path, false, expectedMetadata), + ).rejects.toMatchObject({ + reason: "integrity", + message: `Root artifact changed before inventory: ${path}`, + }); +}); diff --git a/tests/boundary/filesystem/binaryTarget.test.ts b/tests/boundary/filesystem/binaryTarget.test.ts index 69ff26fab..669ee9265 100644 --- a/tests/boundary/filesystem/binaryTarget.test.ts +++ b/tests/boundary/filesystem/binaryTarget.test.ts @@ -24,6 +24,29 @@ import { } from "../../../src/domain/binaryTarget.fixture.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; + +it.skipIf(process.platform === "win32")( + "rejects a selected FIFO without waiting for a writer", + async () => { + const root = await createTestTempDirectory("rea-binary-target-fifo-"); + const fifoPath = join(root, "input.bin"); + await promisify(execFile)("mkfifo", [fifoPath]); + const outcome = await readWithoutFifoWriter(fifoPath, () => + parseBinaryTarget(fifoPath), + ); + expect(outcome.state).toBe("completed"); + if (outcome.state !== "completed") + throw new Error("Binary target resolution waited for a FIFO writer"); + expect(outcome.result).toMatchObject({ + ok: false, + error: { + _tag: "BinaryTargetError", + reason: "target is not a regular file", + }, + }); + }, +); describe("binary target I/O: app plist permissions and decoding", () => { it.each([ diff --git a/tests/boundary/mcp/openBinaryFifo.test.ts b/tests/boundary/mcp/openBinaryFifo.test.ts new file mode 100644 index 000000000..27a2ee1b7 --- /dev/null +++ b/tests/boundary/mcp/openBinaryFifo.test.ts @@ -0,0 +1,48 @@ +import { execFile } from "node:child_process"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { expect, it } from "vitest"; + +import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; + +it.skipIf(process.platform === "win32")( + "rejects an open_binary FIFO without waiting for a writer", + async () => { + const root = await createTestTempDirectory("rea-open-binary-fifo-"); + const fifoPath = join(root, "input.bin"); + await promisify(execFile)("mkfifo", [fifoPath]); + const session = createTestBinarySession(new ArtifactProvider(process.env)); + const server = createServer({ kind: "session", session }); + const client = new Client({ name: "fifo-target-test", version: "1" }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + const outcome = await readWithoutFifoWriter(fifoPath, () => + client.callTool({ name: "open_binary", arguments: { path: fifoPath } }), + ); + expect(outcome.state).toBe("completed"); + if (outcome.state !== "completed") + throw new Error("MCP open_binary waited for a FIFO writer"); + expect(outcome.result.isError).toBe(true); + expect(parseMcpToolError(outcome.result)).toMatchObject({ + error: { message: expect.stringContaining("not a regular file") }, + }); + } finally { + await Promise.allSettled([ + client.close(), + server.close(), + session.close(), + ]); + } + }, +); From 5291bca108af781214572fac709f9808bb8aa4db Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:16:09 +0800 Subject: [PATCH 086/189] refactor(artifacts): remove unused root classifier --- src/artifacts/inventory/classify.ts | 15 --------------- src/filesystem/RegularFile.ts | 1 + tests/boundary/filesystem/zipDetection.test.ts | 12 ++++++++---- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index a8baf7a12..18c675921 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -28,21 +28,6 @@ const classifyContainerExtension = ( return undefined; }; -export const classifyRoot = async ( - path: string, - directory: boolean, -): Promise => { - if (directory) return "directory"; - const extensionFormat = classifyContainerExtension(path); - if (extensionFormat !== undefined) return extensionFormat; - const handle = await openRootFile(path); - try { - return await classifyOpenedRoot(path, handle); - } finally { - await handle.close(); - } -}; - /** Classify and hash one file root through the same stable open descriptor. */ export const classifyAndHashRoot = async ( path: string, diff --git a/src/filesystem/RegularFile.ts b/src/filesystem/RegularFile.ts index e5afac401..13982a896 100644 --- a/src/filesystem/RegularFile.ts +++ b/src/filesystem/RegularFile.ts @@ -2,6 +2,7 @@ import { constants } from "node:fs"; import type { BigIntStats, Stats } from "node:fs"; import { open, type FileHandle } from "node:fs/promises"; +/** Identifies a selected path that cannot be read as one regular file. */ export class NonRegularFileReadError extends Error { readonly code: "EISDIR" | "ENOTFILE"; diff --git a/tests/boundary/filesystem/zipDetection.test.ts b/tests/boundary/filesystem/zipDetection.test.ts index 8ab81112a..3e1878db4 100644 --- a/tests/boundary/filesystem/zipDetection.test.ts +++ b/tests/boundary/filesystem/zipDetection.test.ts @@ -1,9 +1,9 @@ -import { writeFile } from "node:fs/promises"; +import { lstat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { classifyRoot } from "../../../src/artifacts/inventory/classify.js"; +import { classifyAndHashRoot } from "../../../src/artifacts/inventory/classify.js"; import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -19,7 +19,9 @@ describe("ZIP signature detection", () => { const root = await createTestTempDirectory("rea-zip-signature-"); const path = join(root, "input"); await writeFile(path, Buffer.from(signature)); - expect(await classifyRoot(path, false)).toBe(archive ? "zip" : "file"); + expect( + (await classifyAndHashRoot(path, false, await lstat(path))).format, + ).toBe(archive ? "zip" : "file"); const target = await parseBinaryTarget(path); if (archive) expect(target).toMatchObject({ ok: true, value: { format: "zip" } }); @@ -37,7 +39,9 @@ describe("ZIP signature detection", () => { const root = await createTestTempDirectory("rea-zip-short-"); const path = join(root, "input"); await writeFile(path, Buffer.from(bytes)); - expect(await classifyRoot(path, false)).toBe("file"); + expect( + (await classifyAndHashRoot(path, false, await lstat(path))).format, + ).toBe("file"); expect((await parseBinaryTarget(path)).ok).toBe(false); }, ); From 0bfb6e00abae1e67a96e548d64954bb21861f621 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:23:03 +0800 Subject: [PATCH 087/189] test(filesystem): bound FIFO regressions at consumers --- .../artifactInventoryRegularRoot.test.ts | 12 +++++++++- .../boundary/filesystem/binaryTarget.test.ts | 23 ------------------- tests/boundary/mcp/openBinaryFifo.test.ts | 5 +++- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts index b2e4f6d78..00e823ee7 100644 --- a/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts +++ b/tests/boundary/filesystem/artifactInventoryRegularRoot.test.ts @@ -8,6 +8,7 @@ import { expect, it } from "vitest"; import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js"; import { classifyAndHashRoot } from "../../../src/artifacts/inventory/classify.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; it.skipIf(process.platform === "win32")( "rejects a FIFO artifact root without waiting for a writer", @@ -16,7 +17,16 @@ it.skipIf(process.platform === "win32")( const fifoPath = join(root, "input.asar"); await promisify(execFile)("mkfifo", [fifoPath]); - await expect(inventoryArtifact(fifoPath)).rejects.toMatchObject({ + const outcome = await readWithoutFifoWriter(fifoPath, () => + inventoryArtifact(fifoPath).then( + () => undefined, + (cause: unknown) => cause, + ), + ); + expect(outcome.state).toBe("completed"); + if (outcome.state !== "completed") + throw new Error("Artifact inventory waited for a FIFO writer"); + expect(outcome.result).toMatchObject({ reason: "format", message: `Artifact root is not a regular file: ${fifoPath}`, }); diff --git a/tests/boundary/filesystem/binaryTarget.test.ts b/tests/boundary/filesystem/binaryTarget.test.ts index 669ee9265..69ff26fab 100644 --- a/tests/boundary/filesystem/binaryTarget.test.ts +++ b/tests/boundary/filesystem/binaryTarget.test.ts @@ -24,29 +24,6 @@ import { } from "../../../src/domain/binaryTarget.fixture.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; - -it.skipIf(process.platform === "win32")( - "rejects a selected FIFO without waiting for a writer", - async () => { - const root = await createTestTempDirectory("rea-binary-target-fifo-"); - const fifoPath = join(root, "input.bin"); - await promisify(execFile)("mkfifo", [fifoPath]); - const outcome = await readWithoutFifoWriter(fifoPath, () => - parseBinaryTarget(fifoPath), - ); - expect(outcome.state).toBe("completed"); - if (outcome.state !== "completed") - throw new Error("Binary target resolution waited for a FIFO writer"); - expect(outcome.result).toMatchObject({ - ok: false, - error: { - _tag: "BinaryTargetError", - reason: "target is not a regular file", - }, - }); - }, -); describe("binary target I/O: app plist permissions and decoding", () => { it.each([ diff --git a/tests/boundary/mcp/openBinaryFifo.test.ts b/tests/boundary/mcp/openBinaryFifo.test.ts index 27a2ee1b7..aedfc3d6c 100644 --- a/tests/boundary/mcp/openBinaryFifo.test.ts +++ b/tests/boundary/mcp/openBinaryFifo.test.ts @@ -35,7 +35,10 @@ it.skipIf(process.platform === "win32")( throw new Error("MCP open_binary waited for a FIFO writer"); expect(outcome.result.isError).toBe(true); expect(parseMcpToolError(outcome.result)).toMatchObject({ - error: { message: expect.stringContaining("not a regular file") }, + error: { + code: "target_unavailable", + message: expect.stringContaining("not a regular file"), + }, }); } finally { await Promise.allSettled([ From 7ad353fa8b3f07e14face80336678d23cc7c6507 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:29:08 +0800 Subject: [PATCH 088/189] fix(native): retain LLDB cleanup ownership through client close --- src/domain/providerCleanupError.ts | 18 +- src/native/LldbCallTracer.ts | 405 ++++++++++++++---- src/native/NativeCallObservation.test.ts | 6 +- src/native/NativeMacOSProvider.ts | 9 +- src/native/NativeMacOSProviderInput.test.ts | 30 ++ .../mcp/nativeCallObservationMcp.test.ts | 128 +++--- .../native/LldbCallTracer.cleanup.test.ts | 250 +++++++++++ .../native/lldbCallTracerFailures.test.ts | 58 +++ .../native/nativeCallObservation.test.ts | 8 +- 9 files changed, 757 insertions(+), 155 deletions(-) create mode 100644 tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts diff --git a/src/domain/providerCleanupError.ts b/src/domain/providerCleanupError.ts index 8e582caa8..4503b583e 100644 --- a/src/domain/providerCleanupError.ts +++ b/src/domain/providerCleanupError.ts @@ -1,5 +1,6 @@ import type { JsonValue } from "./jsonValue.js"; import { ProviderAdapterError } from "./providerAdapterError.js"; +import type { AnalysisPartialObservation } from "./analysisErrorBase.js"; /** Provider resources could not be proven closed after bounded cleanup. */ export class ProviderCleanupError extends ProviderAdapterError { @@ -13,10 +14,21 @@ export class ProviderCleanupError extends ProviderAdapterError { resources: readonly string[], diagnostics: Readonly>, /** Identify the operation owning these resources; binary callers retain their default. */ - options?: ErrorOptions & { readonly operation?: string }, + options?: ErrorOptions & { + readonly operation?: string; + readonly partialObservation?: AnalysisPartialObservation; + }, ) { - const { operation = "close_binary", ...errorOptions } = options ?? {}; - super(providerId, operation, { ...errorOptions, diagnostics }); + const { + operation = "close_binary", + partialObservation, + ...errorOptions + } = options ?? {}; + super(providerId, operation, { + ...errorOptions, + ...(partialObservation === undefined ? {} : { partialObservation }), + diagnostics, + }); this.cleanupResources = [...resources]; } } diff --git a/src/native/LldbCallTracer.ts b/src/native/LldbCallTracer.ts index c0ea59c8b..9fa5813b8 100644 --- a/src/native/LldbCallTracer.ts +++ b/src/native/LldbCallTracer.ts @@ -12,10 +12,9 @@ import { AnalysisTimeoutError, } from "../domain/analysisErrorCore.js"; import { EvidenceIntegrityError } from "../domain/evidenceErrors.js"; -import type { - AnalysisCleanupObservation, - AnalysisError, -} from "../domain/analysisErrorBase.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js"; import type { NativeCallPartialObservation } from "../domain/native/nativeCallPartialObservation.js"; import { nativeCallEventSchema, @@ -23,6 +22,7 @@ import { type NativeCallObservationInput, } from "../domain/native/nativeCallObservation.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; import { safeParseJson } from "../domain/safeJson.js"; import { @@ -32,7 +32,6 @@ import { import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js"; import { observeProcessStartIdentity, - prepareProcessOwnershipInspection, signalProcessWithStartIdentity, } from "../process/ProcessOwnershipObservation.js"; import type { ProcessIdentityObservation } from "../process/ProcessOwnership.js"; @@ -158,6 +157,8 @@ export interface NativeCallTracer { }, signal?: AbortSignal, ): Promise>; + /** Retry cleanup retained after a trace could not verify process exit. */ + close(): Promise>; } /** Remediation for a target LLDB may not debug. */ @@ -167,6 +168,8 @@ const ATTACH_REMEDIATION = /** Production tracer: `lldb --batch` running the REA LLDB bridge. */ export class LldbCallTracer implements NativeCallTracer { private readonly environment: NodeJS.ProcessEnv; + #tail: Promise = Promise.resolve(); + #pendingCleanup: RetainedLldbResources | undefined; constructor( environment: Readonly, private readonly launch: typeof runLldb = runLldb, @@ -183,6 +186,15 @@ export class LldbCallTracer implements NativeCallTracer { request: Parameters[0], signal?: AbortSignal, ): Promise> { + return this.#serialize(() => this.#trace(request, signal)); + } + + async #trace( + request: Parameters[0], + signal?: AbortSignal, + ): Promise> { + const pendingCleanup = await this.#retryPendingCleanup(); + if (pendingCleanup !== undefined) return err(pendingCleanup); const lldb = await this.resolveTool("lldb", signal); if (!lldb.ok) return err( @@ -196,30 +208,155 @@ export class LldbCallTracer implements NativeCallTracer { ), ); const root = await PrivateRuntimeRoot.create({ prefix: "rea-lldb-" }); + const paths = lldbRuntimePaths(root.path); + let result: Result; try { - return await this.#run(lldb.value, root.path, request, signal); - } finally { - await root.close(); + result = await this.#run(lldb.value, root, request, signal); + } catch (cause: unknown) { + const partialObservation = await partialNativeObservation({ + request, + pidPath: paths.pid, + stdoutPath: paths.stdoutCapture, + stderrPath: paths.stderrCapture, + observationPath: paths.observations, + version: null, + reason: "tracer-failure", + }); + const retained = this.#pendingCleanup; + const resources = + retained === undefined ? [] : await lldbCleanupResources(retained); + result = err( + new ProviderAdapterError(PROVIDER, OPERATION, { + cause, + diagnostics: { + reason: cause instanceof Error ? cause.message : String(cause), + }, + partialObservation, + ...(retained === undefined + ? {} + : { + cleanup: { + reason: "LLDB trace failed while owned resources remain", + resources, + }, + }), + }), + ); } + if (this.#pendingCleanup?.root === root) return result; + try { + await root.close(); + } catch (cause: unknown) { + this.#pendingCleanup = { + root, + supervisor: undefined, + pidPath: paths.pid, + targetIdentity: undefined, + processStopped: true, + targetStopped: true, + }; + const partialObservation = result.ok + ? partialObservationFromTrace(request, result.value) + : result.error.partialObservation; + return err( + new ProviderCleanupError( + PROVIDER, + [root.path], + { + reason: cause instanceof Error ? cause.message : String(cause), + ...(result.ok + ? {} + : { + execution_failure: projectAnalysisError(result.error).code, + primary_failure: result.error.message, + }), + }, + { + operation: OPERATION, + cause: result.ok + ? cause + : new AggregateError( + [result.error, cause], + "LLDB trace and runtime cleanup both failed", + ), + ...(partialObservation === undefined ? {} : { partialObservation }), + }, + ), + ); + } + return result; + } + + /** Retry retained LLDB cleanup without abandoning its process or runtime owner. */ + async close(): Promise> { + return this.#serialize(() => this.#close()); + } + + async #close(): Promise> { + const failure = await this.#retryPendingCleanup(); + return failure === undefined ? ok(null) : err(failure); + } + + #serialize(operation: () => Promise): Promise { + const call = this.#tail.then(operation, operation); + this.#tail = call.then( + () => undefined, + () => undefined, + ); + return call; + } + + async #retryPendingCleanup(): Promise { + const owner = this.#pendingCleanup; + if (owner === undefined) return undefined; + let firstFailure: string | undefined; + if (!owner.processStopped) { + const stopped = await owner.supervisor?.stop(); + if (stopped?.status === "incomplete") firstFailure = stopped.reason; + else { + owner.supervisor?.dispose(); + owner.processStopped = true; + } + } + if (firstFailure === undefined && !owner.targetStopped) { + const targetTermination = await ensureTerminated( + owner.pidPath, + owner.targetIdentity, + true, + ); + if (targetTermination !== "terminated") + firstFailure = targetTerminationReason(targetTermination); + else owner.targetStopped = true; + } + if (firstFailure === undefined) { + try { + await owner.root.close(); + this.#pendingCleanup = undefined; + return undefined; + } catch (cause: unknown) { + firstFailure = cause instanceof Error ? cause.message : String(cause); + } + } + const resources = await lldbCleanupResources(owner); + return new ProviderCleanupError( + PROVIDER, + resources, + { + reason: firstFailure ?? "LLDB cleanup remains incomplete", + resources, + }, + { operation: OPERATION }, + ); } async #run( lldb: ResolvedTool, - directory: string, + root: PrivateRuntimeRoot, request: Parameters[0], signal?: AbortSignal, ): Promise> { - const paths = { - config: join(directory, "config.json"), - result: join(directory, "result.json"), - pid: join(directory, "pid"), - identityAck: join(directory, "identity.ack"), - stdout: join(directory, "stdout"), - stderr: join(directory, "stderr"), - stdoutCapture: join(directory, "stdout.capture"), - stderrCapture: join(directory, "stderr.capture"), - observations: join(directory, "observations.jsonl"), - }; + const directory = root.path; + const paths = lldbRuntimePaths(directory); const { input } = request; await writeFile( paths.config, @@ -251,7 +388,6 @@ export class LldbCallTracer implements NativeCallTracer { }), { mode: 0o600 }, ); - await prepareProcessOwnershipInspection(signal); const exited = await this.launch( lldb.path, [ @@ -271,15 +407,22 @@ export class LldbCallTracer implements NativeCallTracer { ...(signal === undefined ? {} : { signal }), }, ); + const retained: RetainedLldbResources = { + root, + supervisor: exited.cleanupOwner, + pidPath: paths.pid, + targetIdentity: exited.targetIdentity, + processStopped: exited.cleanupOwner === undefined, + targetStopped: !exited.targetLaunched, + }; + this.#pendingCleanup = retained; const output = exited.kind === "exited" ? await readTracerOutput(paths.result) : undefined; - let targetTermination = await ensureTerminated( - paths.pid, - exited.targetIdentity, - true, - ); + let targetTermination: TargetTermination = exited.targetLaunched + ? await ensureTerminated(paths.pid, exited.targetIdentity, true) + : "terminated"; // These two bridge outcomes are emitted before a target process exists. // Other missing-PID cases, including a missing result, remain unknown. if ( @@ -288,6 +431,9 @@ export class LldbCallTracer implements NativeCallTracer { (await readTargetPid(paths.pid)) === undefined ) targetTermination = "terminated"; + retained.targetStopped = targetTermination === "terminated"; + if (retained.processStopped && retained.targetStopped) + this.#pendingCleanup = undefined; const terminated = targetTermination === "terminated"; const cleanupDetails = [ exited.cleanupFailure, @@ -298,16 +444,7 @@ export class LldbCallTracer implements NativeCallTracer { ? undefined : { reason: cleanupDetails.join("; "), - resources: [ - ...(exited.cleanupFailure === undefined - ? [] - : ["lldb-process-group"]), - ...(terminated - ? [] - : [ - `native-target:${String((await readTargetPid(paths.pid)) ?? "unknown")}`, - ]), - ], + resources: await lldbCleanupResources(retained), }; const partialReason = exited.kind === "cancelled" @@ -357,20 +494,38 @@ export class LldbCallTracer implements NativeCallTracer { ); if (exited.cleanupFailure !== undefined) return err( - new ProviderAdapterError(PROVIDER, OPERATION, { - cleanup: lifecycleCleanup ?? { - reason: exited.cleanupFailure, - resources: ["lldb-process-group"], - }, - diagnostics: { + new ProviderCleanupError( + PROVIDER, + await lldbCleanupResources(retained), + { reason: "LLDB process-group cleanup could not be verified", cleanup_failure: exited.cleanupFailure, ...(lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }), }, - partialObservation: await getPartialObservation(), - }), + { + operation: OPERATION, + partialObservation: await getPartialObservation(), + }, + ), + ); + if (!terminated) + return err( + new ProviderCleanupError( + PROVIDER, + await lldbCleanupResources(retained), + { + reason: "LLDB target process termination could not be verified", + ...(lifecycleCleanup === undefined + ? {} + : { target_cleanup: lifecycleCleanup }), + }, + { + operation: OPERATION, + partialObservation: await getPartialObservation(), + }, + ), ); if (output === undefined) return err( @@ -532,6 +687,43 @@ const partialNativeObservation = async (options: { }); }; +const partialObservationFromTrace = ( + request: Parameters[0], + trace: NativeCallTrace, +): NativeCallPartialObservation => + projectLldbPartialObservation({ + target: { + path: request.executable, + sha256: request.expectedSha256, + architecture: request.architecture, + arguments: request.input.arguments, + environment: request.input.environment, + working_directory: request.input.working_directory ?? null, + }, + pid: trace.run.pid, + stdout: trace.stdout, + stderr: trace.stderr, + version: trace.run.version, + journal: { + events: trace.run.events, + otherStops: trace.run.other_stops, + limitations: [], + }, + reason: "cleanup-failure", + }); + +const lldbRuntimePaths = (directory: string) => ({ + config: join(directory, "config.json"), + result: join(directory, "result.json"), + pid: join(directory, "pid"), + identityAck: join(directory, "identity.ack"), + stdout: join(directory, "stdout"), + stderr: join(directory, "stderr"), + stdoutCapture: join(directory, "stdout.capture"), + stderrCapture: join(directory, "stderr.capture"), + observations: join(directory, "observations.jsonl"), +}); + const readTracerOutput = async ( path: string, ): Promise | undefined> => { @@ -588,24 +780,43 @@ const capturedOutput = async ( } }; -type LldbExit = +interface RetainedLldbResources { + readonly root: PrivateRuntimeRoot; + readonly supervisor: ProviderProcessSupervisor | undefined; + readonly pidPath: string; + readonly targetIdentity: string | undefined; + processStopped: boolean; + targetStopped: boolean; +} + +type LldbOutcome = | { readonly kind: "exited"; readonly exitCode: number | null; readonly output: string; - readonly targetIdentity: string | undefined; - readonly cleanupFailure: string | undefined; } - | { - readonly kind: "cancelled"; - readonly targetIdentity: string | undefined; - readonly cleanupFailure: string | undefined; - } - | { - readonly kind: "timeout"; - readonly targetIdentity: string | undefined; - readonly cleanupFailure: string | undefined; - }; + | { readonly kind: "cancelled" } + | { readonly kind: "timeout" }; + +type LldbExit = LldbOutcome & { + /** False proves LLDB never started and could not have created a target. */ + readonly targetLaunched: boolean; + readonly targetIdentity: string | undefined; + readonly cleanupFailure: string | undefined; + readonly cleanupOwner?: ProviderProcessSupervisor; +}; + +const lldbCleanupResources = async ( + owner: RetainedLldbResources, +): Promise => [ + ...(owner.processStopped ? [] : ["lldb-process-group"]), + ...(owner.targetStopped + ? [] + : [ + `native-target:${String((await readTargetPid(owner.pidPath)) ?? "unknown")}`, + ]), + owner.root.path, +]; /** Supervise LLDB as an owned process group while observing its target PID identity. */ const runLldb = async ( @@ -622,6 +833,7 @@ const runLldb = async ( if (options.signal?.aborted === true) return { kind: "cancelled", + targetLaunched: false, targetIdentity: undefined, cleanupFailure: undefined, }; @@ -631,6 +843,23 @@ const runLldb = async ( ); let targetIdentity: string | undefined; let supervisor: ProviderProcessSupervisor | undefined; + let retained = false; + const finish = async (outcome: LldbOutcome): Promise => { + const stopped = await supervisor?.stop(); + retained = stopped?.status === "incomplete"; + return { + ...(deadline.interruption === undefined + ? outcome + : { kind: deadline.interruption }), + targetLaunched: supervisor !== undefined, + targetIdentity, + cleanupFailure: + stopped?.status === "incomplete" ? stopped.reason : undefined, + ...(retained && supervisor !== undefined + ? { cleanupOwner: supervisor } + : {}), + }; + }; try { const launched = await spawnOwnedProviderProcess({ command: executable, @@ -668,52 +897,36 @@ const runLldb = async ( identityAckWritten = true; } const interruption = deadline.interruption; - if (interruption !== undefined) { - const stopped = await supervisor.stop(); - const cleanupFailure = - stopped.status === "incomplete" ? stopped.reason : undefined; - return interruption === "cancelled" - ? { kind: "cancelled", targetIdentity, cleanupFailure } - : { kind: "timeout", targetIdentity, cleanupFailure }; - } + if (interruption !== undefined) + return await finish({ kind: interruption }); await waitForAbortableDelay(20, deadline.signal); } const snapshot = supervisor.snapshot(); - const stopped = await supervisor.stop(); - const cleanupFailure = - stopped.status === "incomplete" ? stopped.reason : undefined; const interruption = deadline.interruption; - if (interruption === "cancelled") - return { kind: "cancelled", targetIdentity, cleanupFailure }; - if (interruption === "timeout") - return { kind: "timeout", targetIdentity, cleanupFailure }; - return { - kind: "exited", - exitCode: snapshot.exitCode ?? null, - output: `${snapshot.stdout.text}${snapshot.stderr.text}`.slice( - -DIAGNOSTIC_BYTES, - ), - targetIdentity, - cleanupFailure, - }; + return await finish( + interruption === undefined + ? { + kind: "exited", + exitCode: snapshot.exitCode ?? null, + output: `${snapshot.stdout.text}${snapshot.stderr.text}`.slice( + -DIAGNOSTIC_BYTES, + ), + } + : { kind: interruption }, + ); } catch (cause: unknown) { const interruption = deadline.interruption; - const stopped = await supervisor?.stop(); - const cleanupFailure = - stopped?.status === "incomplete" ? stopped.reason : undefined; - return interruption === "timeout" - ? { kind: "timeout", targetIdentity, cleanupFailure } - : interruption === "cancelled" - ? { kind: "cancelled", targetIdentity, cleanupFailure } - : { + return await finish( + interruption === undefined + ? { kind: "exited", exitCode: null, output: cause instanceof Error ? cause.message : String(cause), - targetIdentity, - cleanupFailure, - }; + } + : { kind: interruption }, + ); } finally { - supervisor?.dispose(); + if (!retained) supervisor?.dispose(); deadline.dispose(); } }; @@ -724,8 +937,10 @@ const runLldb = async ( */ const readTargetPid = async (pidPath: string): Promise => { try { - const pid = Number.parseInt(await readFile(pidPath, "utf8"), 10); - return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined; + const contents = (await readFile(pidPath, "utf8")).trim(); + if (!/^[1-9]\d*$/u.test(contents)) return undefined; + const pid = Number(contents); + return Number.isSafeInteger(pid) ? pid : undefined; } catch { return undefined; } diff --git a/src/native/NativeCallObservation.test.ts b/src/native/NativeCallObservation.test.ts index fcff10565..15b9b2604 100644 --- a/src/native/NativeCallObservation.test.ts +++ b/src/native/NativeCallObservation.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from "vitest"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { err, type Result } from "../domain/result.js"; +import { ok, type Result } from "../domain/result.js"; import type { NativeCallTrace, NativeCallTracer } from "./LldbCallTracer.js"; import { observeNativeCalls } from "./NativeCallObservation.js"; import { nativeMachoTarget } from "../../tests/fixtures/nativeCommands.js"; @@ -20,6 +20,10 @@ class NeverStartedTracer implements NativeCallTracer { this.calls += 1; throw new Error("tracer must not run after hash cancellation"); } + + close(): Promise> { + return Promise.resolve(ok(null)); + } } describe("native call target digest cancellation", () => { diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index 0d25f969c..12c94814f 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -82,6 +82,7 @@ import { export class NativeMacOSProvider implements AnalysisProvider { readonly #capabilities: readonly CapabilityDescriptor[]; readonly #environment: NodeJS.ProcessEnv; + readonly #tracerFactory: () => NativeCallTracer; constructor( environment: Readonly, @@ -89,9 +90,11 @@ export class NativeMacOSProvider implements AnalysisProvider { environment, ), platform: NodeJS.Platform = process.platform, - private readonly tracer: NativeCallTracer = new LldbCallTracer(environment), + tracerFactory?: () => NativeCallTracer, ) { this.#environment = snapshotEnvironment(environment, platform); + this.#tracerFactory = + tracerFactory ?? (() => new LldbCallTracer(this.#environment)); this.#capabilities = nativeMacOSCapabilities(platform); } @@ -107,7 +110,7 @@ export class NativeMacOSProvider implements AnalysisProvider { return new NativeMacOSClient( target, this.runner, - this.tracer, + this.#tracerFactory(), this.#environment, ); } @@ -246,7 +249,7 @@ class NativeMacOSClient implements AnalysisClient { } close(): Promise> { - return Promise.resolve(ok(null)); + return this.tracer.close(); } #dispatch( diff --git a/src/native/NativeMacOSProviderInput.test.ts b/src/native/NativeMacOSProviderInput.test.ts index df4131e69..a795bf76c 100644 --- a/src/native/NativeMacOSProviderInput.test.ts +++ b/src/native/NativeMacOSProviderInput.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { NativeMacOSProvider } from "./NativeMacOSProvider.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { ok } from "../domain/result.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { NativeFixtureRunner, @@ -57,4 +58,33 @@ describe("native dispatch metadata input boundary", () => { }); } }); + + it("closes only the native call tracer owned by that client", async () => { + const closes = [0, 0]; + let next = 0; + const provider = new NativeMacOSProvider( + {}, + new NativeFixtureRunner(), + "darwin", + () => { + const index = next++; + return { + trace: async () => { + throw new Error("trace is unused in this lifecycle test"); + }, + close: async () => { + closes[index] = (closes[index] ?? 0) + 1; + return ok(null); + }, + }; + }, + ); + const first = provider.createClient(nativeMachoTarget("/first")); + const second = provider.createClient(nativeMachoTarget("/second")); + + expect((await first.close()).ok).toBe(true); + expect(closes).toEqual([1, 0]); + expect((await second.close()).ok).toBe(true); + expect(closes).toEqual([1, 1]); + }); }); diff --git a/tests/boundary/mcp/nativeCallObservationMcp.test.ts b/tests/boundary/mcp/nativeCallObservationMcp.test.ts index cecd3b2f4..52c26c282 100644 --- a/tests/boundary/mcp/nativeCallObservationMcp.test.ts +++ b/tests/boundary/mcp/nativeCallObservationMcp.test.ts @@ -81,6 +81,7 @@ const tracer: NativeCallTracer & { calls: number } = { }), ); }, + close: () => Promise.resolve(ok(null)), }; it("routes observe_native_calls through MCP with schema-checked input and output", async () => { @@ -88,7 +89,12 @@ it("routes observe_native_calls through MCP with schema-checked input and output const path = join(directory, "Tool"); await writeFile(path, machoHeader()); const session = createTestBinarySession( - new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer), + new NativeMacOSProvider( + {}, + new NativeFixtureRunner(), + "darwin", + () => tracer, + ), ); const server = createServer({ kind: "session", session }); const client = new Client({ name: "native-calls-mcp-test", version: "1" }); @@ -138,6 +144,62 @@ it("routes observe_native_calls through MCP with schema-checked input and output } }); +const partialObservationFor = (options: { + readonly path: string; + readonly sha256: string; + readonly arguments: string[]; + readonly environment: Record; + readonly workingDirectory: string; + readonly reason: "cancelled" | "cleanup-failure"; +}) => + nativeCallPartialObservationSchema.parse({ + kind: "native-call-observation", + target: { + path: options.path, + sha256: options.sha256, + architecture: "arm64", + arguments: options.arguments, + environment: options.environment, + working_directory: options.workingDirectory, + }, + process: { + pid: 4242, + stdout: { + text: "partial target output", + bytes: 21, + truncated: true, + complete: false, + }, + stderr: { + text: "debugger diagnostic", + bytes: 19, + truncated: false, + complete: false, + }, + other_stops: ["signal SIGSTOP"], + }, + debugger: { version: "lldb-fixture" }, + events: [ + { + sequence: 0, + elapsed_ms: 4, + thread_id: 3, + breakpoint_index: 0, + load_address: "0x1000", + file_address: "0x1000", + module: "Tool", + module_path: options.path, + symbol: "open", + receiver_class: null, + selector: null, + registers: [{ name: "x0", value: "0x2" }], + backtrace: [], + }, + ], + coverage: { status: "partial", reason: options.reason }, + limitations: ["Observation ended before the requested window completed."], + }); + it.each([ ["cancelled", "cancelled", undefined], [ @@ -161,57 +223,16 @@ it.each([ const launchArguments = ["--fixture", "selected argument"]; const launchEnvironment = { REA_NATIVE_FIXTURE: "selected value" }; const workingDirectory = directory; - const partialObservation = nativeCallPartialObservationSchema.parse({ - kind: "native-call-observation", - target: { - path, - sha256, - architecture: "arm64", - arguments: launchArguments, - environment: launchEnvironment, - working_directory: workingDirectory, - }, - process: { - pid: 4242, - stdout: { - text: "partial target output", - bytes: 21, - truncated: true, - complete: false, - }, - stderr: { - text: "debugger diagnostic", - bytes: 19, - truncated: false, - complete: false, - }, - other_stops: ["signal SIGSTOP"], - }, - debugger: { version: "lldb-fixture" }, - events: [ - { - sequence: 0, - elapsed_ms: 4, - thread_id: 3, - breakpoint_index: 0, - load_address: "0x1000", - file_address: "0x1000", - module: "Tool", - module_path: path, - symbol: "open", - receiver_class: null, - selector: null, - registers: [{ name: "x0", value: "0x2" }], - backtrace: [], - }, - ], - coverage: { - status: "partial", - reason: cleanup === undefined ? "cancelled" : "cleanup-failure", - }, - limitations: ["Observation ended before the requested window completed."], + const partialObservation = partialObservationFor({ + path, + sha256, + arguments: launchArguments, + environment: launchEnvironment, + workingDirectory, + reason: cleanup === undefined ? "cancelled" : "cleanup-failure", }); const tracer: NativeCallTracer = { + close: () => Promise.resolve(ok(null)), trace: () => Promise.resolve( err( @@ -231,7 +252,12 @@ it.each([ ), }; const session = createTestBinarySession( - new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer), + new NativeMacOSProvider( + {}, + new NativeFixtureRunner(), + "darwin", + () => tracer, + ), ); const server = createServer({ kind: "session", session }); const client = new Client({ diff --git a/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts b/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts new file mode 100644 index 000000000..b3e365d5c --- /dev/null +++ b/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts @@ -0,0 +1,250 @@ +import { randomUUID } from "node:crypto"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { access, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it } from "vitest"; + +import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js"; +import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js"; +import { ok } from "../../../../src/domain/result.js"; +import { cleanupOwnedProcessGroup } from "../../../../src/process/ProcessOwnership.js"; +import { observeProcessStartIdentity } from "../../../../src/process/ProcessOwnershipObservation.js"; +import { + ProviderProcessSupervisor, + spawnOwnedProviderProcess, +} from "../../../../src/process/ProviderProcess.js"; +import type { NativeCallTracer } from "../../../../src/native/LldbCallTracer.js"; +import { LldbCallTracer } from "../../../../src/native/LldbCallTracer.js"; +import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js"; +import { + NativeFixtureRunner, + nativeMachoTarget, +} from "../../../fixtures/nativeCommands.js"; + +const request: Parameters[0] = { + executable: "/fixture/target", + architecture: "arm64", + expectedSha256: "0".repeat(64), + input: { + breakpoints: [{ kind: "function", name: "main" }], + arguments: [], + environment: {}, + duration_ms: 100, + max_events: 1, + argument_registers: 0, + backtrace_frames: 0, + }, +}; +const tool = { path: process.execPath, sha256: "0".repeat(64) }; + +const createTracer = ( + launch?: ConstructorParameters[1], +): LldbCallTracer => + new LldbCallTracer(process.env, launch, async () => ok(tool)); + +const createClient = (tracer: NativeCallTracer) => + new NativeMacOSProvider( + {}, + new NativeFixtureRunner(), + "darwin", + () => tracer, + ).createClient(nativeMachoTarget(request.executable)); + +const runtimeRoot = (error: ProviderCleanupError): string => { + const root = error.cleanupResources.find((resource) => + resource.startsWith(`${tmpdir()}/rea-lldb-`), + ); + if (root === undefined) throw new Error("Expected retained runtime root"); + return root; +}; + +const liveChild = async () => { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { + stdio: "ignore", + }); + await once(child, "spawn"); + if (child.pid === undefined) throw new Error("Fixture process had no PID"); + return { child, pid: child.pid }; +}; + +const stopChild = async (child: ReturnType) => { + if (child.exitCode === null && child.signalCode === null) { + const exited = once(child, "exit"); + child.kill("SIGKILL"); + await exited; + } +}; + +it.skipIf(process.platform === "win32")( + "retains a real LLDB process owner and runtime until a later cleanup retry succeeds", + async () => { + let cleanupFailures = 2; + let ownedPid: number | undefined; + const tracer = createTracer(async (_exe, _args, options) => { + const target = spawn(process.execPath, ["-e", "process.exit(0)"], { + stdio: "ignore", + }); + await once(target, "exit"); + if (target.pid === undefined) + throw new Error("Fixture target had no PID"); + await writeFile(options.pidPath, String(target.pid)); + const launched = await spawnOwnedProviderProcess({ + command: process.execPath, + arguments: ["-e", "setInterval(() => {}, 1000)"], + runId: randomUUID(), + hostEnvironment: options.environment, + }); + ownedPid = launched.process.pid; + const supervisor = new ProviderProcessSupervisor({ + ...launched, + ownsProcessLifetime: true, + cleanup: async () => { + if (cleanupFailures-- > 0) + return { + cleaned: false, + reason: "fixture transient cleanup failure", + }; + return cleanupOwnedProcessGroup(launched.ownership); + }, + }); + const stopped = await supervisor.stop(); + return { + kind: "exited" as const, + targetLaunched: true, + exitCode: null, + output: "", + targetIdentity: undefined, + cleanupFailure: + stopped.status === "incomplete" ? stopped.reason : undefined, + ...(stopped.status === "incomplete" + ? { cleanupOwner: supervisor } + : {}), + }; + }); + const client = createClient(tracer); + + try { + const trace = await tracer.trace(request); + expect(trace.ok).toBe(false); + if (trace.ok) throw new Error("Expected incomplete cleanup"); + expect(trace.error).toBeInstanceOf(ProviderCleanupError); + if (!(trace.error instanceof ProviderCleanupError)) return; + expect(trace.error.cleanupResources).toContain("lldb-process-group"); + expect(trace.error.partialObservation).toBeDefined(); + const root = runtimeRoot(trace.error); + await expect(access(root)).resolves.toBeUndefined(); + if (ownedPid === undefined) throw new Error("Expected owned process PID"); + const pid = ownedPid; + expect(() => process.kill(pid, 0)).not.toThrow(); + expect((await client.close()).ok).toBe(false); + expect(() => process.kill(pid, 0)).not.toThrow(); + await expect(access(root)).resolves.toBeUndefined(); + expect((await client.close()).ok).toBe(true); + expect(() => process.kill(pid, 0)).toThrow(); + await expect(access(root)).rejects.toThrow(); + } finally { + await client.close(); + } + }, +); + +it.skipIf(process.platform === "win32")( + "does not retain a target when cancellation proves LLDB never launched", + async () => { + const controller = new AbortController(); + const cancelledTracer = new LldbCallTracer( + process.env, + undefined, + async () => { + controller.abort(); + return ok(tool); + }, + ); + const result = await cancelledTracer.trace(request, controller.signal); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Expected cancelled trace"); + expect(result.error).toBeInstanceOf(AnalysisCancelledError); + expect((await cancelledTracer.close()).ok).toBe(true); + }, +); + +it.skipIf(process.platform === "win32")( + "retains an unidentified debuggee and runtime until exit can be confirmed", + async () => { + const { child, pid } = await liveChild(); + const tracer = createTracer(async (_exe, _args, options) => { + await writeFile(options.pidPath, String(pid)); + return { + kind: "exited", + targetLaunched: true, + exitCode: 0, + output: "", + targetIdentity: undefined, + cleanupFailure: undefined, + }; + }); + const client = createClient(tracer); + + try { + const trace = await tracer.trace(request); + expect(trace.ok).toBe(false); + if (trace.ok) throw new Error("Expected unverified target cleanup"); + expect(trace.error).toBeInstanceOf(ProviderCleanupError); + if (!(trace.error instanceof ProviderCleanupError)) return; + expect(trace.error.cleanupResources).toContain(`native-target:${pid}`); + const root = runtimeRoot(trace.error); + await expect(access(root)).resolves.toBeUndefined(); + expect(() => process.kill(pid, 0)).not.toThrow(); + expect((await client.close()).ok).toBe(false); + expect(() => process.kill(pid, 0)).not.toThrow(); + await expect(access(root)).resolves.toBeUndefined(); + await stopChild(child); + expect((await client.close()).ok).toBe(true); + await expect(access(root)).rejects.toThrow(); + } finally { + await stopChild(child); + await client.close(); + } + }, +); + +it.skipIf(process.platform === "win32")( + "rejects malformed PID authority and retries after the target exits", + async () => { + const { child, pid } = await liveChild(); + const identity = await observeProcessStartIdentity(pid); + if (identity?.state !== "readable") + throw new Error("Host could not read fixture process identity"); + const tracer = createTracer(async (_exe, _args, options) => { + await writeFile(options.pidPath, `${pid}junk`); + return { + kind: "exited", + targetLaunched: true, + exitCode: 0, + output: "", + targetIdentity: identity.identity, + cleanupFailure: undefined, + }; + }); + const client = createClient(tracer); + + try { + const trace = await tracer.trace(request); + expect(trace.ok).toBe(false); + if (trace.ok) throw new Error("Expected malformed PID cleanup failure"); + expect(trace.error).toBeInstanceOf(ProviderCleanupError); + if (!(trace.error instanceof ProviderCleanupError)) return; + expect(trace.error.cleanupResources).toContain("native-target:unknown"); + expect(() => process.kill(pid, 0)).not.toThrow(); + const root = runtimeRoot(trace.error); + await stopChild(child); + await writeFile(join(root, "pid"), String(pid)); + expect((await client.close()).ok).toBe(true); + } finally { + await stopChild(child); + await client.close(); + } + }, +); diff --git a/tests/boundary/providers/native/lldbCallTracerFailures.test.ts b/tests/boundary/providers/native/lldbCallTracerFailures.test.ts index 6f10e6b20..a8d65dedb 100644 --- a/tests/boundary/providers/native/lldbCallTracerFailures.test.ts +++ b/tests/boundary/providers/native/lldbCallTracerFailures.test.ts @@ -12,6 +12,12 @@ import type { NativeCallTracer } from "../../../../src/native/LldbCallTracer.js" import { LldbCallTracer } from "../../../../src/native/LldbCallTracer.js"; import { err, ok } from "../../../../src/domain/result.js"; import { NativeCommandFailure } from "../../../../src/native/CommandRunner.js"; +import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js"; +import { createDeferred } from "../../../fixtures/binarySession.js"; +import { + NativeFixtureRunner, + nativeMachoTarget, +} from "../../../fixtures/nativeCommands.js"; const EVENT = { sequence: 0, @@ -83,11 +89,13 @@ const fixtureTracer = ( return outcome === "cancelled" ? { kind: "cancelled", + targetLaunched: false, targetIdentity: undefined, cleanupFailure: undefined, } : { kind: "exited", + targetLaunched: false, exitCode: 1, output: "bridge reported target integrity failure", targetIdentity: undefined, @@ -108,6 +116,56 @@ const fixtureTracer = ( }; describe("LLDB failure retention through the production tracer", () => { + it("waits for an active trace before client close removes its runtime root", async () => { + const launchGate = createDeferred(); + const launchStarted = createDeferred(); + const tracer = new LldbCallTracer( + {}, + async (_executable, arguments_) => { + const { config } = await configFromArguments(arguments_); + await writeFile( + config.observation_path, + `${JSON.stringify({ kind: "event", event: EVENT })}\n`, + ); + await writeFile(config.stdout_capture_path, "captured prefix"); + launchStarted.resolve(); + await launchGate.promise; + return { + kind: "exited", + targetLaunched: false, + exitCode: 0, + output: "", + targetIdentity: undefined, + cleanupFailure: undefined, + }; + }, + async () => ok(fakeTool), + ); + const client = new NativeMacOSProvider( + {}, + new NativeFixtureRunner(), + "darwin", + () => tracer, + ).createClient(nativeMachoTarget(request.executable)); + const tracePromise = tracer.trace(request); + await launchStarted.promise; + let closeFinished = false; + const closePromise = client.close().then((result) => { + closeFinished = true; + return result; + }); + await Promise.resolve(); + expect(closeFinished).toBe(false); + launchGate.resolve(); + const [trace, close] = await Promise.all([tracePromise, closePromise]); + expect(close.ok).toBe(true); + if (trace.ok) throw new Error("expected missing LLDB result"); + expect(trace.error.partialObservation).toMatchObject({ + events: [EVENT], + process: { stdout: { text: "captured prefix", complete: false } }, + }); + }); + it("names the missing LLDB requirement instead of asking for another target", async () => { const tracer = new LldbCallTracer( {}, diff --git a/tests/boundary/providers/native/nativeCallObservation.test.ts b/tests/boundary/providers/native/nativeCallObservation.test.ts index 0ae599748..c915da0d9 100644 --- a/tests/boundary/providers/native/nativeCallObservation.test.ts +++ b/tests/boundary/providers/native/nativeCallObservation.test.ts @@ -108,6 +108,10 @@ class FixtureTracer implements NativeCallTracer { this.requests.push(request); return Promise.resolve(this.outcome); } + + close() { + return Promise.resolve(ok(null)); + } } const BREAKPOINTS = [ @@ -131,7 +135,7 @@ const observe = async ( target?: Awaited>, signal?: AbortSignal, ) => - new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer) + new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", () => tracer) .createClient(target ?? (await fixtureTarget())) .execute( "observe_native_calls", @@ -421,7 +425,7 @@ describe("observe_native_calls failures", () => { {}, new NativeFixtureRunner(), "darwin", - tracer, + () => tracer, ) .createClient({ path: target.path, From 048b79878c70c594789909082499dc675472b63a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:39:17 +0800 Subject: [PATCH 089/189] test(native): retain trace diagnostics when observed hits differ --- scripts/verify-native-calls.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/verify-native-calls.mjs b/scripts/verify-native-calls.mjs index 62c9a2b19..7a2262075 100644 --- a/scripts/verify-native-calls.mjs +++ b/scripts/verify-native-calls.mjs @@ -95,8 +95,8 @@ const checkScenario = async (binary) => { }); const greet = result.events.filter(({ symbol }) => symbol === GREET); const add = result.events.filter(({ symbol }) => symbol === "rea_call_add"); - assert.equal(greet.length, 3); - assert.equal(add.length, 3); + assert.equal(greet.length, 3, JSON.stringify(result)); + assert.equal(add.length, 3, JSON.stringify(result)); for (const [index, event] of greet.entries()) { assert.equal(event.receiver_class, "ReaCallGreeter"); assert.equal(event.selector, "greet:times:"); From f39e71ce1897bb5c704b33a8b0049567f11e3a13 Mon Sep 17 00:00:00 2001 From: yi111 <153097222+Yi-111-a@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:47:10 +0800 Subject: [PATCH 090/189] fix(skill): pin packaged commands to the shipping package version (#1346) Fixes #1338. Use canonical product identity for bundled command versions and keep build-cache fixtures aligned. Verified 10 focused tests, actual CLI installation/repair/uninstall scenarios and all 19 final-head CI checks. Co-authored-by: Yi-111-a <97448247+Yi-111-a@users.noreply.github.com> --- scripts/generate-skill-metadata.mjs | 8 ++++---- tests/boundary/filesystem/dependencyInstall.test.ts | 7 ++++--- tests/boundary/filesystem/generatedSkill.test.ts | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/scripts/generate-skill-metadata.mjs b/scripts/generate-skill-metadata.mjs index 931163e3b..5bb2e3ccf 100644 --- a/scripts/generate-skill-metadata.mjs +++ b/scripts/generate-skill-metadata.mjs @@ -20,8 +20,8 @@ const cacheBust = String(Date.now()); const { CATALOG_IDENTITY } = await import( `${pathToFileURL(join(root, "dist/catalogIdentity.js")).href}?${cacheBust}` ); -const { PACKAGE_METADATA } = await import( - `${pathToFileURL(join(root, "dist/generatedPackageMetadata.js")).href}?${cacheBust}` +const { PRODUCT_IDENTITY } = await import( + `${pathToFileURL(join(root, "dist/identity.js")).href}?${cacheBust}` ); if (/^\s{2}(?:tool_count|catalog_digest):/mu.test(current)) throw new Error( @@ -31,8 +31,8 @@ const versionLine = /^ {2}version: "[^"\r\n]+"$/mu; if (!versionLine.test(current)) throw new Error("Missing authored skill version"); // A shipped skill must run the version it ships with, not whatever `@latest` resolves to. -const latestSpecifier = `${PACKAGE_METADATA.name}@latest`; -const pinnedSpecifier = `${PACKAGE_METADATA.name}@${PACKAGE_METADATA.version}`; +const latestSpecifier = PRODUCT_IDENTITY.packageSpecifier; +const pinnedSpecifier = PRODUCT_IDENTITY.registrationPackageSpecifier; const source = current .replace( versionLine, diff --git a/tests/boundary/filesystem/dependencyInstall.test.ts b/tests/boundary/filesystem/dependencyInstall.test.ts index 967d1a839..66378360f 100644 --- a/tests/boundary/filesystem/dependencyInstall.test.ts +++ b/tests/boundary/filesystem/dependencyInstall.test.ts @@ -151,6 +151,8 @@ const createBuildCacheFixture = async (): Promise => { const scripts = asRecord(packageJson?.scripts); if ( packageJson === undefined || + typeof packageJson.name !== "string" || + typeof packageJson.version !== "string" || typeof scripts?.["build:cached"] !== "string" ) throw new Error("package is missing its cached build command"); @@ -189,12 +191,11 @@ const createBuildCacheFixture = async (): Promise => { ); await writeFile( join(root, "scripts/cache-fixture-build.mjs"), - `import { mkdir, readFile, writeFile } from "node:fs/promises"; -const { name, version } = JSON.parse(await readFile("package.json", "utf8")); + `import { mkdir, writeFile } from "node:fs/promises"; await mkdir("dist", { recursive: true }); await writeFile("dist/cache-fixture.js", "built"); await writeFile("dist/catalogIdentity.js", "export const CATALOG_IDENTITY = { counts: { mcp_tools: 1 } };\\n"); -await writeFile("dist/generatedPackageMetadata.js", "export const PACKAGE_METADATA = " + JSON.stringify({ name, version }) + ";\\n"); +await writeFile("dist/identity.js", ${JSON.stringify(`export const PRODUCT_IDENTITY = ${JSON.stringify({ packageSpecifier: `${packageJson.name}@latest`, registrationPackageSpecifier: `${packageJson.name}@${packageJson.version}` })};\n`)}); `, ); await createNodeModulesLinks(root); diff --git a/tests/boundary/filesystem/generatedSkill.test.ts b/tests/boundary/filesystem/generatedSkill.test.ts index f35e0abb6..5df6e3146 100644 --- a/tests/boundary/filesystem/generatedSkill.test.ts +++ b/tests/boundary/filesystem/generatedSkill.test.ts @@ -27,8 +27,8 @@ async function fixture(eol = "\n") { await mkdir(join(root, "dist")); await writeFile(join(root, "package.json"), '{"type":"module"}\n'); await writeFile( - join(root, "dist/generatedPackageMetadata.js"), - 'export const PACKAGE_METADATA = { name: "rea-agents", version: "6.2.0" };\n', + join(root, "dist/identity.js"), + 'export const PRODUCT_IDENTITY = { packageSpecifier: "rea-agents@latest", registrationPackageSpecifier: "rea-agents@6.2.0" };\n', ); await writeFile(join(sourceRoot, "SKILL.md"), authored.replaceAll("\n", eol)); await writeFile( From 3728c8267b4fb6da78cbae42a2a6cbddff80ea84 Mon Sep 17 00:00:00 2001 From: Dery Ferdika <114888155+DeryFerd@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:52:25 +0700 Subject: [PATCH 091/189] fix(ghidra): reject a native decompiler built for another host (#1280) Reject positively identified foreign-only Ghidra decompiler binaries and non-regular native prerequisites before provider startup, while retaining unknown classifications for incomplete or unrecognized headers. Verified with 54 focused tests and real Linux Ghidra CLI/MCP admission, decompilation, cleanup, wrong-host PE rejection, and non-blocking FIFO rejection. All 19 final-head checks passed. Fixes #1192 Co-authored-by: Dery Ferdika <114888155+DeryFerd@users.noreply.github.com> --- docs/installation.md | 7 +- src/ghidra/GhidraInstallation.test.ts | 169 ++++++++++++++++++++++ src/ghidra/GhidraInstallation.ts | 193 ++++++++++++++++++++++++-- 3 files changed, 356 insertions(+), 13 deletions(-) diff --git a/docs/installation.md b/docs/installation.md index 1152dd848..c47062a6f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -472,8 +472,11 @@ and JDK 21. Each installation must include the native decompiler for the host architecture in `Ghidra/Features/Decompiler/os//` or the corresponding `build/os//` directory. Linux ARM64 uses `linux_arm_64`; official release archives may require you to build that native component separately. -REA checks the executable prerequisite and does not build or install native -tools, or change Gatekeeper quarantine settings. +REA checks the executable prerequisite by inspecting the file's own executable +header, so a native component built for another platform or architecture is +reported as incompatible instead of being admitted from its directory name, and +a header that cannot be read or recognized is reported as unknown. REA does not +build or install native tools, or change Gatekeeper quarantine settings. The adapter exposes 25 read-only operations: thirteen inventory/name/search operations and twelve function-analysis operations. These cover metadata, diff --git a/src/ghidra/GhidraInstallation.test.ts b/src/ghidra/GhidraInstallation.test.ts index d81447c8d..4f5dfce63 100644 --- a/src/ghidra/GhidraInstallation.test.ts +++ b/src/ghidra/GhidraInstallation.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { elf, fat, thinMach } from "../domain/binaryTarget.fixture.js"; import { projectGhidraDoctorInspection } from "./GhidraDoctor.js"; import { ghidraJavaEnvironment, @@ -510,3 +511,171 @@ describe("Ghidra configuration paths", () => { ); }); }); + +describe("Ghidra FAT native decompiler admission", () => { + it.each([ + { + name: "foreign-only FAT", + bytes: fat([0x01000007]), + status: "unavailable", + detail: "requires mach-o arm64", + }, + { + name: "matching universal FAT", + bytes: fat([0x01000007, 0x0100000c]), + status: "available", + detail: "matches darwin/arm64", + }, + { + name: "truncated FAT table", + bytes: fat([0x01000007], 2), + status: "available", + detail: "could not be established", + }, + ])("distinguishes $name", ({ bytes, status, detail }) => { + const result = inspectGhidraInstallation( + { + environment: {}, + installDir: INSTALL, + platform: "darwin", + architecture: "arm64", + }, + host({ executableHeader: () => ({ bytes, size: bytes.length }) }), + ); + expect(result.status).toBe(status); + expect( + result.checks.find(({ name }) => name === "native_decompiler")?.detail, + ).toContain(detail); + }); + + it("keeps a truncated host slice unknown despite a readable foreign slice", () => { + const bytes = fat([0x01000007, 0x0100000c]); + bytes.writeUInt32BE(bytes.length + 1, 8 + 20 + 12); + const result = inspectGhidraInstallation( + { + environment: {}, + installDir: INSTALL, + platform: "darwin", + architecture: "arm64", + }, + host({ executableHeader: () => ({ bytes, size: bytes.length }) }), + ); + expect(result.status).toBe("available"); + expect( + result.checks.find(({ name }) => name === "native_decompiler")?.detail, + ).toContain("could not be established"); + }); +}); + +describe("Ghidra native decompiler admission", () => { + it.each([ + { + name: "a Linux x86-64 decompiler at the macOS arm64 path", + options: { + environment: {}, + installDir: INSTALL, + platform: "darwin" as const, + architecture: "arm64" as const, + }, + executableHeader: (path: string) => + path === MAC_DECOMPILER + ? { bytes: elf(2, 1, 62), size: 52 } + : undefined, + }, + { + name: "a macOS arm64 decompiler at the Linux x64 path", + options: { + environment: {}, + installDir: INSTALL, + platform: "linux" as const, + architecture: "x64" as const, + }, + executableHeader: (path: string) => + path === LINUX_DECOMPILER + ? { bytes: thinMach(0xcffaedfe, 0x0100000c), size: 32 } + : undefined, + }, + ])("distinguishes $name", ({ options, executableHeader }) => { + const result = inspectGhidraInstallation( + options, + host({ executableHeader }), + ); + expect(result.status).toBe("unavailable"); + expect( + result.checks.find(({ status }) => status === "failed"), + ).toMatchObject({ name: "native_decompiler", code: "executable_missing" }); + }); + + it("explains an accepted decompiler by its header, not only its path", () => { + const result = inspectGhidraInstallation( + { + environment: {}, + installDir: INSTALL, + platform: "linux", + architecture: "x64", + }, + host({ + executableHeader: (path: string) => + path === LINUX_DECOMPILER + ? { bytes: elf(2, 1, 62), size: 52 } + : undefined, + }), + ); + expect(result.status).toBe("available"); + if (result.status !== "available") return; + expect( + result.checks.find(({ name }) => name === "native_decompiler"), + ).toMatchObject({ + status: "passed", + detail: `${LINUX_DECOMPILER} reports elf x86_64, which matches linux/x64`, + }); + }); + + it("keeps an unreadable header unknown instead of failing the install", () => { + const result = inspectGhidraInstallation( + { + environment: {}, + installDir: INSTALL, + platform: "linux", + architecture: "x64", + }, + host({ executableHeader: () => undefined }), + ); + expect(result.status).toBe("available"); + if (result.status !== "available") return; + expect( + result.checks.find(({ name }) => name === "native_decompiler"), + ).toMatchObject({ + status: "passed", + detail: expect.stringContaining("could not be established"), + }); + }); + + it("names the observed and the required executable in the failure", () => { + const result = inspectGhidraInstallation( + { + environment: {}, + installDir: INSTALL, + platform: "darwin", + architecture: "arm64", + }, + host({ + executableHeader: (path: string) => + path === MAC_DECOMPILER + ? { bytes: elf(2, 1, 62), size: 52 } + : undefined, + }), + ); + expect(result.status).toBe("unavailable"); + if (result.status !== "unavailable") return; + expect( + result.checks.find(({ name }) => name === "native_decompiler"), + ).toMatchObject({ + status: "failed", + detail: expect.stringMatching( + /reports elf x86_64, but darwin\/arm64 requires mach-o arm64/u, + ), + remediation: expect.stringContaining("os/mac_arm_64/decompile"), + }); + }); +}); diff --git a/src/ghidra/GhidraInstallation.ts b/src/ghidra/GhidraInstallation.ts index c01d8d475..d60d447ed 100644 --- a/src/ghidra/GhidraInstallation.ts +++ b/src/ghidra/GhidraInstallation.ts @@ -1,10 +1,23 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import { spawnSync } from "node:child_process"; import { constants } from "node:fs"; -import { accessSync, readFileSync } from "node:fs"; +import { + accessSync, + closeSync, + fstatSync, + openSync, + readFileSync, + readSync, + statSync, +} from "node:fs"; import { posix, win32 } from "node:path"; import type { ProviderRejectionCode } from "../contracts/providerSelection.js"; +import { + parseExecutableHeader, + type ExecutableMetadata, +} from "../domain/binaryTarget.js"; +import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { ghidraApplicationProperties, @@ -34,6 +47,103 @@ const NATIVE_PLATFORMS: Readonly< win32: { x64: "win_x86_64" }, }; +/** Executable format each supported host runs its own Ghidra native tools as. */ +const NATIVE_TOOL_FORMATS: Readonly< + Partial> +> = { + linux: "elf", + darwin: "mach-o", + win32: "pe", +}; + +/** Node architecture identifiers as the executable-header parser reports them. */ +const NATIVE_ARCHITECTURES: readonly { + readonly node: NodeJS.Architecture; + readonly binary: BinaryArchitecture; +}[] = [ + { node: "x64", binary: "x86_64" }, + { node: "ia32", binary: "x86" }, + { node: "arm", binary: "arm" }, + { node: "arm64", binary: "arm64" }, +]; + +/** Bound installation discovery reads; larger headers remain unknown. */ +const EXECUTABLE_HEADER_PROBE_BYTES = 4096; + +/** Compatibility of one present native decompiler with the inspected host. */ +type NativeDecompilerCompatibility = + | { + readonly status: "incompatible"; + readonly detail: string; + readonly remediation: string; + } + | { readonly status: "compatible"; readonly detail: string } + | { readonly status: "unknown"; readonly detail: string }; + +/** + * Judge a native decompiler by its own executable header instead of the + * directory name that admits it. + * + * Only a header that positively contradicts the host is `incompatible`. An + * absent, unreadable, truncated, or unrecognized header stays `unknown`, so a + * file the other checks already accept is never refused on missing evidence. + */ +const assessNativeDecompiler = ( + path: string, + platform: NodeJS.Platform, + architecture: NodeJS.Architecture, + probe: GhidraExecutableHeaderProbe | undefined, +): NativeDecompilerCompatibility => { + const expectedFormat = NATIVE_TOOL_FORMATS[platform]; + const expectedArchitecture = NATIVE_ARCHITECTURES.find( + ({ node }) => node === architecture, + )?.binary; + if (expectedFormat === undefined || expectedArchitecture === undefined) + return { + status: "unknown", + detail: `${path} is executable, but no native tool format is defined for ${platform}/${architecture}`, + }; + let parsed = + probe === undefined + ? undefined + : parseExecutableHeader(probe.bytes, architecture, probe.size); + if (probe !== undefined && parsed !== undefined && !parsed.ok) { + // FAT parsing selects a host slice. A validated foreign slice can still + // prove that its complete architecture table excludes this host. If the + // host is listed but its slice is malformed, preserve the unknown outcome. + for (const { node } of NATIVE_ARCHITECTURES) { + if (node === architecture) continue; + const alternative = parseExecutableHeader(probe.bytes, node, probe.size); + if ( + alternative.ok && + !alternative.value.availableArchitectures.includes(expectedArchitecture) + ) { + parsed = alternative; + break; + } + } + } + if (parsed === undefined || !parsed.ok) + return { + status: "unknown", + detail: `${path} is executable, but its executable format for ${platform}/${architecture} could not be established`, + }; + const observed = `${parsed.value.format} ${parsed.value.architecture}`; + const expected = `${expectedFormat} ${expectedArchitecture}`; + if (observed === expected) + return { + status: "compatible", + detail: `${path} reports ${observed}, which matches ${platform}/${architecture}`, + }; + const nativeDirectory = NATIVE_PLATFORMS[platform]?.[architecture]; + const executable = platform === "win32" ? "decompile.exe" : "decompile"; + return { + status: "incompatible", + detail: `${path} reports ${observed}, but ${platform}/${architecture} requires ${expected}`, + remediation: `Provide an executable Ghidra/Features/Decompiler/os/${nativeDirectory ?? ""}/${executable} built for ${expected}, or its build/os equivalent. REA does not build or install native tools.`, + }; +}; + /** Caller-owned paths and host coordinates used for one installation probe. */ export interface GhidraInstallationOptions { readonly environment: Readonly; @@ -117,12 +227,27 @@ export interface GhidraJavaObservation { readonly runtime: "jdk" | "jre"; } +/** A bounded executable-header probe: a small prefix plus the whole file size. */ +export interface GhidraExecutableHeaderProbe { + /** A bounded prefix; a larger or unreadable header remains unknown. */ + readonly bytes: Buffer; + /** Whole-file size, since header commitments are checked against it, not the prefix. */ + readonly size: number; +} + /** Narrow synchronous seam used by provider discovery without launching Ghidra. */ export interface GhidraInstallationHost { readonly platform?: NodeJS.Platform; readonly architecture?: NodeJS.Architecture; readText(path: string): string | undefined; executable(path: string): boolean; + /** + * Read a bounded header prefix of one executable so admission can reject a + * tool built for another platform or architecture. An omitted seam, or an + * unreadable file, reports the header as unknown and never rejects an + * installation that the other checks already accept. + */ + executableHeader?(path: string): GhidraExecutableHeaderProbe | undefined; probeJava( command: string, environment: NodeJS.ProcessEnv, @@ -352,15 +477,7 @@ const installationChecks = ({ remediation: "Restore support/analyzeHeadless or support/analyzeHeadless.bat from the official Ghidra release.", }), - installationCheck({ - name: "native_decompiler", - passed: coordinates.nativeDecompilerPath !== null, - code: "executable_missing", - detail: - coordinates.nativeDecompilerPath ?? - `Matching native decompiler for ${platform}/${architecture} was not found`, - remediation: `Provide an executable Ghidra/Features/Decompiler/os/${NATIVE_PLATFORMS[platform]?.[architecture] ?? ""}/${platform === "win32" ? "decompile.exe" : "decompile"}, or its build/os equivalent. REA does not build or install native tools.`, - }), + nativeDecompilerCheck({ coordinates, platform, architecture, host }), javaCheck( coordinates.java, coordinates.javaCommand, @@ -472,6 +589,40 @@ const installationCheck = (options: { remediation: options.remediation, }; +/** Require a present native decompiler without positively incompatible bytes. */ +const nativeDecompilerCheck = ({ + coordinates, + platform, + architecture, + host, +}: Pick< + GhidraInstallationCheckContext, + "coordinates" | "platform" | "architecture" | "host" +>): GhidraInstallationCheck => { + const path = coordinates.nativeDecompilerPath; + const compatibility = + path === null + ? undefined + : assessNativeDecompiler( + path, + platform, + architecture, + host.executableHeader?.(path), + ); + return installationCheck({ + name: "native_decompiler", + passed: path !== null && compatibility?.status !== "incompatible", + code: "executable_missing", + detail: + compatibility?.detail ?? + `Matching native decompiler for ${platform}/${architecture} was not found`, + remediation: + compatibility?.status === "incompatible" + ? compatibility.remediation + : `Provide an executable Ghidra/Features/Decompiler/os/${NATIVE_PLATFORMS[platform]?.[architecture] ?? ""}/${platform === "win32" ? "decompile.exe" : "decompile"}, or its build/os equivalent. REA does not build or install native tools.`, + }); +}; + const versionCheck = ( properties: GhidraApplicationProperties | undefined, ): GhidraInstallationCheck => { @@ -543,10 +694,30 @@ const systemGhidraInstallationHost = (): GhidraInstallationHost => ({ return undefined; } }, + executableHeader(path) { + let handle: number | undefined; + try { + handle = openSync( + path, + constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY, + ); + const metadata = fstatSync(handle); + if (!metadata.isFile()) return undefined; + const bytes = Buffer.alloc(EXECUTABLE_HEADER_PROBE_BYTES); + const read = readSync(handle, bytes, 0, bytes.length, 0); + return { bytes: bytes.subarray(0, read), size: metadata.size }; + } catch (cause: unknown) { + // best-effort cleanup: a header that cannot be read stays unknown. + void cause; + return undefined; + } finally { + if (handle !== undefined) closeSync(handle); + } + }, executable(path) { try { accessSync(path, constants.X_OK); - return true; + return statSync(path).isFile(); } catch (cause: unknown) { // best-effort cleanup: optional executable probing; failure means missing. void cause; From 6ce3288f3bd65a886e47905455ed5c9b661015e6 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:53:09 +0800 Subject: [PATCH 092/189] fix(cli): stream JSON inputs beyond the whole-document string limit (#1360) Stream large CLI JSON files through a strict UTF-8 decoder and standard JSON parser using the same admitted regular-file handle. Preserve native parsing for small inputs, typed malformed-input/resource/access-denied errors, cancellation, and complete Evidence. Verified with focused public CLI regressions, a 768 MB whitespace-padded valid request, and the Windows native decoder boundary. Individual strings and the assembled object graph remain subject to native runtime limits. All 27 final-head checks passed. Refs #1331 --- docs/javascript-artifact-reconstruction.md | 20 +- package-lock.json | 22 ++ package.json | 1 + src/application/JsonFiles.ts | 25 +- src/application/RegularFileRead.ts | 23 +- src/application/Utf8JsonInput.ts | 7 +- src/cliJsonFile.ts | 261 ++++++++++++++++++ src/cliJsonInput.ts | 79 ++---- tests/boundary/cli/jsonInputSize.test.ts | 118 +++++++- .../boundary/filesystem/cliJsonInput.test.ts | 196 +++++++------ 10 files changed, 555 insertions(+), 197 deletions(-) create mode 100644 src/cliJsonFile.ts diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md index 881b244d6..3a996e5f9 100644 --- a/docs/javascript-artifact-reconstruction.md +++ b/docs/javascript-artifact-reconstruction.md @@ -113,11 +113,21 @@ smaller view, for example `--format json --filter-output evidence_id,normalized_result.statistics`. Streaming output does not bound the memory needed to construct the analysis graph itself. -CLI workflows still parse each JSON input as one value. A valid input exceeding -the Node runtime's maximum string length returns `resource_constraint` with -`input_reason: "too-large"` and the runtime limit. Produce smaller independent -analysis inputs before retrying; streaming output does not imply streaming -input parsing. +CLI workflows parse larger JSON input files incrementally from one verified +regular-file handle, without constructing a document-sized string. Smaller +files retain native JSON parsing. Both paths require strict JSON and valid +UTF-8, and return one complete value; the assembled object still needs memory. +An individual JSON string exceeding the native length limit or the available +heap headroom for assembly returns +`resource_constraint` with `input_reason: "too-large"`. Supply a smaller valid +value; for Evidence workflows, re-analyze a smaller selection of the original +target and use its complete Evidence. Splitting JSON text or trimming Evidence +fields does not produce a valid workflow input. + +Evidence bundle and analysis snapshot file readers still decode whole +documents. Their runtime string-limit failures report a resource constraint +with the selected path, observed bytes and UTF-16 limit, rather than malformed +JSON. MCP prepares the complete repeated response incrementally against the pinned SDK's 10 MiB stdio receive-buffer budget. Oversized results return an actionable diff --git a/package-lock.json b/package-lock.json index 9e674e202..212d6b8eb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "plist": "5.0.0", "semver": "7.8.5", "smol-toml": "1.9.0", + "stream-json": "3.7.0", "write-file-atomic": "7.0.0", "ws": "8.21.0", "zod": "4.4.3" @@ -7070,6 +7071,27 @@ "dev": true, "license": "MIT" }, + "node_modules/stream-chain": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/stream-chain/-/stream-chain-4.2.6.tgz", + "integrity": "sha512-1zeJ8CrtJfmiba26ui8jXkq/xLRFvhzkdH02D5QLO9Cnovgeb28IJxg88DdraWnjnkbOol/++uIAybJbJhk7ig==", + "license": "BSD-3-Clause", + "funding": { + "url": "https://github.com/sponsors/uhop" + } + }, + "node_modules/stream-json": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/stream-json/-/stream-json-3.7.0.tgz", + "integrity": "sha512-rCSBdcBP/bPk6T8QFcxAj1MSzAuc5i49cYW6IE7sYObNEPccBJIUiL6fU9c9BWt40aJK0siVynLX7lWaW8alXw==", + "license": "BSD-3-Clause", + "dependencies": { + "stream-chain": "^4.2.5" + }, + "funding": { + "url": "https://github.com/sponsors/uhop" + } + }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", diff --git a/package.json b/package.json index 0ec211497..a3d3bb0e1 100644 --- a/package.json +++ b/package.json @@ -263,6 +263,7 @@ "plist": "5.0.0", "semver": "7.8.5", "smol-toml": "1.9.0", + "stream-json": "3.7.0", "write-file-atomic": "7.0.0", "ws": "8.21.0", "zod": "4.4.3", diff --git a/src/application/JsonFiles.ts b/src/application/JsonFiles.ts index 8132255da..0ccca760a 100644 --- a/src/application/JsonFiles.ts +++ b/src/application/JsonFiles.ts @@ -3,7 +3,6 @@ import { lstat, mkdtemp, open, - readFile, realpath, rename, rm, @@ -18,6 +17,8 @@ import { } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; import { parseUtf8Json } from "./Utf8JsonInput.js"; +import { readRegularFile } from "./RegularFileRead.js"; +import { NonRegularFileReadError } from "../filesystem/RegularFile.js"; /** Request control and its owning operation for an interruptible atomic write. */ export interface TextWriteCancellation { @@ -36,13 +37,7 @@ export const readJsonFile = async ( > => { const requestedPath = resolve(path); try { - const canonicalPath = await realpath(requestedPath); - const stats = await lstat(canonicalPath); - if (!stats.isFile()) - return err( - new EvidenceFileError("read", "not-file", { path: requestedPath }), - ); - const encoded = await readFile(canonicalPath); + const encoded = await readRegularFile(requestedPath); const decoded = parseUtf8Json(encoded, "read_evidence_file", requestedPath); if (!decoded.ok) { return err( @@ -56,10 +51,16 @@ export const readJsonFile = async ( } catch (cause: unknown) { if (cause instanceof AnalysisResourceConstraintError) return err(cause); return err( - new EvidenceFileError("read", missingOrIo(cause), { - cause, - path: requestedPath, - }), + new EvidenceFileError( + "read", + cause instanceof NonRegularFileReadError + ? "not-file" + : missingOrIo(cause), + { + cause, + path: requestedPath, + }, + ), ); } }; diff --git a/src/application/RegularFileRead.ts b/src/application/RegularFileRead.ts index 486e8c54d..df87b7c5a 100644 --- a/src/application/RegularFileRead.ts +++ b/src/application/RegularFileRead.ts @@ -1,16 +1,29 @@ +import type { Stats } from "node:fs"; +import type { FileHandle } from "node:fs/promises"; + import { openRegularFile } from "../filesystem/RegularFile.js"; -/** Admit a regular file without waiting for a pipe, then read its verified handle. */ -export const readRegularFile = async ( +/** Admit one regular-file handle, retain it through the consumer, and always close it. */ +export const withRegularFile = async ( path: string, + read: (handle: FileHandle, stats: Stats) => Promise, signal?: AbortSignal, -): Promise => { +): Promise => { const handle = await openRegularFile(path, { symlinks: "follow", signal }); try { - const bytes = await handle.readFile({ signal }); + const stats = await handle.stat(); signal?.throwIfAborted(); - return bytes; + const value = await read(handle, stats); + signal?.throwIfAborted(); + return value; } finally { await handle.close(); } }; + +/** Admit a regular file without waiting for a pipe, then read its verified handle. */ +export const readRegularFile = ( + path: string, + signal?: AbortSignal, +): Promise => + withRegularFile(path, (handle) => handle.readFile({ signal }), signal); diff --git a/src/application/Utf8JsonInput.ts b/src/application/Utf8JsonInput.ts index 4b9ecf10b..86204e3c9 100644 --- a/src/application/Utf8JsonInput.ts +++ b/src/application/Utf8JsonInput.ts @@ -3,6 +3,10 @@ import { constants } from "node:buffer"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; import { safeParseJson, type SafeJsonParseResult } from "../domain/safeJson.js"; +/** Recovery that preserves complete, authenticated Evidence workflow inputs. */ +export const JSON_INPUT_RESOURCE_REMEDIATION = + "Provide a smaller valid JSON value. For Evidence workflows, re-analyze a smaller selection of the original target and use its complete Evidence; splitting JSON text or trimming Evidence fields does not produce valid workflow input."; + /** Decode JSON bytes without confusing a runtime string limit with malformed input. */ export const parseUtf8Json = ( bytes: Uint8Array, @@ -29,8 +33,7 @@ export const parseUtf8Json = ( }, { ...(cause === undefined ? {} : { cause }), - remediationAction: - "Provide a smaller JSON document. For Evidence-based workflows, re-analyze a smaller selection of the original target and use its Evidence; splitting JSON text alone does not produce a valid workflow input.", + remediationAction: JSON_INPUT_RESOURCE_REMEDIATION, }, ); let text: string; diff --git a/src/cliJsonFile.ts b/src/cliJsonFile.ts new file mode 100644 index 000000000..ea75f7c29 --- /dev/null +++ b/src/cliJsonFile.ts @@ -0,0 +1,261 @@ +import { constants } from "node:buffer"; +import type { FileHandle } from "node:fs/promises"; +import { pipeline } from "node:stream/promises"; +import { getHeapStatistics } from "node:v8"; + +import parser from "stream-json/parser.js"; +import streamValues from "stream-json/streamers/stream-values.js"; + +import { withRegularFile } from "./application/RegularFileRead.js"; +import { + JSON_INPUT_RESOURCE_REMEDIATION, + parseUtf8Json, +} from "./application/Utf8JsonInput.js"; +import { + AnalysisInputError, + AnalysisResourceConstraintError, +} from "./domain/analysisErrorCore.js"; +import { err, ok, type Result } from "./domain/result.js"; + +type JsonFileFailure = AnalysisInputError | AnalysisResourceConstraintError; +const READ_CHUNK_BYTES = 64 * 1024; +const PACKED_STRING_PART_CODE_UNITS = 64 * 1024; +// Retain native-parser speed for modest inputs while bounding its extra copies. +// This selects an implementation; larger files remain accepted through streaming. +const NATIVE_PARSE_READ_BUDGET = 8 * 1024 * 1024; + +/** Parse strict UTF-8 JSON without requiring a whole-document string. */ +export const readCliJsonFile = ( + path: string, + operation: string, + signal?: AbortSignal, +): Promise> => + withRegularFile( + path, + async (handle, stats) => { + let found = false; + let value: unknown; + try { + const prefix = + stats.size <= NATIVE_PARSE_READ_BUDGET + ? await readPrefix(handle, stats.size + 1, signal) + : undefined; + if (prefix?.complete === true) { + const parsed = parseUtf8Json( + prefix.bytes, + operation, + path, + "cli-json-input", + ); + return parsed.ok + ? ok(parsed.value) + : err(invalidJson(operation, parsed.error, parsed.cause)); + } + await pipeline( + decodedChunks(handle, signal, prefix?.bytes), + parser.asStream({ + jsonStreaming: false, + streamValues: false, + packKeys: false, + packStrings: false, + }), + packJsonStrings(operation, stats.size), + streamValues.asStream(), + async (rows: AsyncIterable) => { + for await (const row of rows) { + if ( + found || + typeof row !== "object" || + row === null || + !("key" in row) || + row.key !== 0 || + !("value" in row) + ) + throw new Error("Unexpected JSON parser result"); + found = true; + value = row.value; + } + }, + signal === undefined ? {} : { signal }, + ); + return found + ? ok(value) + : err(invalidJson(operation, "JSON document is empty")); + } catch (cause: unknown) { + if (cause instanceof AnalysisResourceConstraintError) return err(cause); + if ( + cause instanceof TypeError && + "code" in cause && + cause.code === "ERR_ENCODING_INVALID_ENCODED_DATA" + ) + return err( + invalidJson(operation, "JSON input is not valid UTF-8", cause), + ); + if ( + cause instanceof SyntaxError || + (cause instanceof Error && cause.message.startsWith("Parser ")) + ) + return err(invalidJson(operation, cause.message, cause)); + if ( + cause instanceof Error && + ((cause instanceof RangeError && + cause.message === "Invalid string length") || + ("code" in cause && cause.code === "ERR_STRING_TOO_LONG")) + ) + return err( + new AnalysisResourceConstraintError( + operation, + "memory", + "An individual JSON string exceeds the runtime string limit", + { + input_file_bytes: stats.size, + max_string_code_units: constants.MAX_STRING_LENGTH, + }, + { + cause, + remediationAction: JSON_INPUT_RESOURCE_REMEDIATION, + }, + ), + ); + throw cause; + } + }, + signal, + ); + +const packJsonStrings = (operation: string, inputFileBytes: number) => + async function* (tokens: AsyncIterable): AsyncGenerator { + let kind: "keyValue" | "stringValue" | undefined; + let length = 0; + let value = ""; + let parts: string[] = []; + let partLength = 0; + for await (const token of tokens) { + if (typeof token !== "object" || token === null || !("name" in token)) + throw new Error("Unexpected JSON parser token"); + switch (token.name) { + case "startKey": + case "startString": + kind = token.name === "startKey" ? "keyValue" : "stringValue"; + break; + case "stringChunk": + if ( + kind === undefined || + !("value" in token) || + typeof token.value !== "string" + ) + throw new Error("Unexpected JSON string fragment"); + length += token.value.length; + if (length > constants.MAX_STRING_LENGTH) + throw new RangeError("Invalid string length"); + parts.push(token.value); + partLength += token.value.length; + if (partLength >= PACKED_STRING_PART_CODE_UNITS) { + // The tokenizer emits short fragments. Coalesce them before retaining + // a string so millions of substring/rope nodes cannot exhaust the heap + // before the native string-length constraint can be reported. + requireStringAssemblyHeadroom(operation, inputFileBytes, length); + value += parts.join(""); + parts = []; + partLength = 0; + } + break; + case "endKey": + case "endString": + if (kind === undefined) throw new Error("Unexpected JSON string end"); + requireStringAssemblyHeadroom(operation, inputFileBytes, length); + yield { name: kind, value: value + parts.join("") }; + kind = undefined; + length = 0; + value = ""; + parts = []; + partLength = 0; + break; + default: + yield token; + } + } + }; + +const requireStringAssemblyHeadroom = ( + operation: string, + inputFileBytes: number, + stringCodeUnits: number, +): void => { + if (stringCodeUnits < PACKED_STRING_PART_CODE_UNITS) return; + const heap = getHeapStatistics(); + // Concatenation or key interning may flatten the retained rope. Reserve its + // UTF-16 representation and the next coalesced part before that allocation. + const requiredBytes = 2 * (stringCodeUnits + PACKED_STRING_PART_CODE_UNITS); + if (requiredBytes > heap.total_available_size) + throw new AnalysisResourceConstraintError( + operation, + "memory", + "Insufficient heap headroom to assemble a complete JSON string", + { + input_file_bytes: inputFileBytes, + string_code_units: stringCodeUnits, + string_assembly_headroom_bytes: requiredBytes, + available_heap_bytes: heap.total_available_size, + heap_size_limit_bytes: heap.heap_size_limit, + }, + { + remediationAction: JSON_INPUT_RESOURCE_REMEDIATION, + }, + ); +}; + +async function* decodedChunks( + handle: FileHandle, + signal: AbortSignal | undefined, + prefix?: Uint8Array, +): AsyncGenerator { + const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + if (prefix !== undefined) + for (let offset = 0; offset < prefix.length; offset += READ_CHUNK_BYTES) { + signal?.throwIfAborted(); + yield decoder.decode(prefix.subarray(offset, offset + READ_CHUNK_BYTES), { + stream: true, + }); + } + const bytes = Buffer.allocUnsafe(READ_CHUNK_BYTES); + while (true) { + signal?.throwIfAborted(); + const read = await handle.read(bytes, 0, bytes.length, null); + signal?.throwIfAborted(); + if (read.bytesRead === 0) break; + yield decoder.decode(bytes.subarray(0, read.bytesRead), { stream: true }); + } + yield decoder.decode(); +} + +const readPrefix = async ( + handle: FileHandle, + size: number, + signal: AbortSignal | undefined, +): Promise<{ readonly bytes: Buffer; readonly complete: boolean }> => { + const bytes = Buffer.allocUnsafe(size); + let offset = 0; + while (offset < bytes.length) { + signal?.throwIfAborted(); + const read = await handle.read(bytes, offset, bytes.length - offset, null); + signal?.throwIfAborted(); + if (read.bytesRead === 0) + return { bytes: bytes.subarray(0, offset), complete: true }; + offset += read.bytesRead; + } + // The file grew after admission. Continue from this same handle, preserving + // the prefix already read rather than reopening or dropping its bytes. + return { bytes, complete: false }; +}; + +const invalidJson = ( + operation: string, + message: string, + cause?: unknown, +): AnalysisInputError => + new AnalysisInputError( + operation, + cause === undefined ? undefined : { cause }, + [{ path: [], reason: "invalid_format", expected: "JSON", message }], + ); diff --git a/src/cliJsonInput.ts b/src/cliJsonInput.ts index ebab099fe..47b1431e4 100644 --- a/src/cliJsonInput.ts +++ b/src/cliJsonInput.ts @@ -1,13 +1,10 @@ -import { constants as bufferConstants } from "node:buffer"; import { resolve } from "node:path"; -import { readRegularFile } from "./application/RegularFileRead.js"; +import { readCliJsonFile } from "./cliJsonFile.js"; import { NonRegularFileReadError } from "./filesystem/RegularFile.js"; -import { parseUtf8Json } from "./application/Utf8JsonInput.js"; import { AnalysisAccessDeniedError, AnalysisInputError, - AnalysisResourceConstraintError, } from "./domain/analysisErrorCore.js"; import { projectAnalysisError } from "./domain/analysisErrorProjection.js"; import type { JsonValue } from "./domain/jsonValue.js"; @@ -23,31 +20,23 @@ export const parseCliJsonInput = async ( > => { const inline = safeParseJson(value); if (inline.ok) return { ok: true, value: inline.value }; - if (isStringLengthLimit(inline.cause)) - return jsonTooLargeError(undefined, operation); try { - // Read raw bytes so invalid UTF-8 is rejected instead of - // being silently replaced by lossy "utf8" decoding. - const parsed = parseUtf8Json( - await readRegularFile(value), - operation, - value, - "cli-json-input", - ); + const parsed = await readCliJsonFile(value, operation); return parsed.ok ? { ok: true, value: parsed.value } - : jsonFileError(value, operation, "invalid-json"); + : { + ok: false, + error: { + error: "Application workflow failed", + ...projectAnalysisError(parsed.error), + input_path: value, + input_reason: + parsed.error._tag === "AnalysisInputError" + ? "invalid-json" + : "too-large", + }, + }; } catch (cause: unknown) { - if (cause instanceof AnalysisResourceConstraintError) - return { - ok: false, - error: { - error: "Application workflow failed", - ...projectAnalysisError(cause), - input_path: value, - input_reason: "too-large", - }, - }; const systemCode = accessDeniedSystemCode(cause); if (systemCode !== undefined) return jsonAccessDeniedError(value, operation, systemCode, cause); @@ -57,6 +46,12 @@ export const parseCliJsonInput = async ( !hasExplicitJsonFileExtension(value) ) return { ok: false, error: inputError(operation) }; + if ( + !(cause instanceof Error) || + !("code" in cause) || + typeof cause.code !== "string" + ) + throw cause; return jsonFileError(value, operation, "read-failed", cause); } }; @@ -120,13 +115,6 @@ const cannotBeAnExistingFile = (cause: unknown): boolean => const hasExplicitJsonFileExtension = (value: string): boolean => value.toLowerCase().endsWith(".json"); -const isStringLengthLimit = (cause: unknown): boolean => - cause instanceof Error && - (("code" in cause && cause.code === "ERR_STRING_TOO_LONG") || - /cannot create a string longer than|invalid string length/i.test( - cause.message, - )); - const inputError = (operation: string): JsonValue => ({ error: "Application workflow failed", ...projectAnalysisError( @@ -194,30 +182,3 @@ const readFailureIssue = (path: string | undefined, cause: unknown) => { : `The JSON input file could not be read${code}: ${path ?? ""}`, }; }; - -const jsonTooLargeError = ( - path: string | undefined, - operation: string, -): { readonly ok: false; readonly error: JsonValue } => ({ - ok: false, - error: { - error: "Application workflow failed", - ...projectAnalysisError( - new AnalysisResourceConstraintError( - operation, - "memory", - `The JSON input exceeds this Node.js runtime's maximum string length (${bufferConstants.MAX_STRING_LENGTH} UTF-16 code units) and cannot be parsed as one value.`, - { - boundary: "cli-json-input", - max_string_code_units: bufferConstants.MAX_STRING_LENGTH, - }, - { - remediationAction: - "Provide a smaller JSON document or rerun its producer on a smaller selection. Splitting JSON text alone does not produce a valid workflow input.", - }, - ), - ), - ...(path === undefined ? {} : { input_path: path }), - input_reason: "too-large", - }, -}); diff --git a/tests/boundary/cli/jsonInputSize.test.ts b/tests/boundary/cli/jsonInputSize.test.ts index fce9412f2..13e99eafa 100644 --- a/tests/boundary/cli/jsonInputSize.test.ts +++ b/tests/boundary/cli/jsonInputSize.test.ts @@ -1,5 +1,5 @@ import { constants } from "node:buffer"; -import { open } from "node:fs/promises"; +import { mkdir, open, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; @@ -8,14 +8,14 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; cliTest( - "preserves the runtime string limit through CLI and Evidence file inputs", + "rejects malformed oversized CLI input and preserves Evidence decoder resource failures", async ({ cli, processes }) => { const root = await createTestTempDirectory("rea-json-string-limit-"); const input = join(root, "oversized.json"); const file = await open(input, "wx"); try { - // Sparse zero bytes are valid UTF-8. Decoded length exceeds the runtime - // string limit before JSON syntax can be inspected; no fixture is retained. + // Sparse zero bytes are valid UTF-8. The Evidence reader reaches the + // decoded-length limit; the streamed CLI rejects their invalid JSON syntax. await file.truncate(constants.MAX_STRING_LENGTH + 1); } finally { await file.close(); @@ -31,17 +31,9 @@ cliTest( arguments: ["trace-application-feature", input, "--json"], }); expect(result.json).toMatchObject({ - code: "resource_constraint", - category: "resource_constraint", + code: "invalid_request", input_path: input, - input_reason: "too-large", - retryable: false, - remediation: { action: expect.stringContaining("re-analyze") }, - details: { - operation: "trace-application-feature", - resource: "memory", - reported_limits: limits, - }, + input_reason: "invalid-json", }); expect(result.exitCode).toBe(1); expect(result.stderr).toBe(""); @@ -67,3 +59,101 @@ cliTest( expect(evidence.exitCode).toBe(0); }, ); + +cliTest( + "traces valid Evidence beyond the whole-document string limit", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-json-streamed-evidence-"); + const source = join(root, "application"); + await mkdir(source); + await writeFile( + join(source, "package.json"), + JSON.stringify({ + name: "streamed-evidence", + type: "module", + main: "entry.mjs", + }), + ); + await writeFile( + join(source, "entry.mjs"), + 'export const observed = "source-owned";', + ); + const application = await cli.run({ + arguments: [ + "analyze-javascript-application", + source, + "--artifact-format", + "directory", + "--json", + ], + }); + expect(application.exitCode).toBe(0); + const request = JSON.stringify({ + application: application.json, + seed: { kind: "module", value: "entry.mjs", match: "contains" }, + direction: "incoming", + }); + const input = join(root, "trace.json"); + await writeFile(input, request); + const ordinary = await cli.run({ + arguments: ["trace-application-feature", input, "--json"], + }); + expect(ordinary.exitCode).toBe(0); + const file = await open(input, "a"); + try { + const whitespace = Buffer.alloc(1024 * 1024, 0x20); + let remaining = + constants.MAX_STRING_LENGTH + 1 - Buffer.byteLength(request); + while (remaining > 0) { + const length = Math.min(remaining, whitespace.length); + await file.writeFile(whitespace.subarray(0, length)); + remaining -= length; + } + } finally { + await file.close(); + } + const streamed = await cli.run({ + arguments: ["trace-application-feature", input, "--json"], + }); + expect(streamed.exitCode).toBe(0); + expect(streamed.json).toEqual(ordinary.json); + expect(streamed.stderr).toBe(""); + }, +); + +cliTest( + "returns a typed string assembly constraint under a bounded heap", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-json-string-headroom-"); + const input = join(root, "long-string.json"); + const file = await open(input, "wx"); + try { + await file.writeFile('"'); + const chunk = Buffer.alloc(1024 * 1024, 0x78); + let remaining = constants.MAX_STRING_LENGTH + 1; + while (remaining > 0) { + const length = Math.min(remaining, chunk.length); + await file.writeFile(chunk.subarray(0, length)); + remaining -= length; + } + await file.writeFile('"'); + } finally { + await file.close(); + } + const result = await cli.run({ + arguments: ["trace-application-feature", input, "--json"], + environment: { NODE_OPTIONS: "--max-old-space-size=768" }, + }); + expect(result.exitCode, result.stderr).toBe(1); + expect(result.stderr).toBe(""); + expect(result.json).toMatchObject({ + code: "resource_constraint", + input_path: input, + input_reason: "too-large", + details: { resource: "memory" }, + remediation: { + action: expect.stringContaining("re-analyze a smaller selection"), + }, + }); + }, +); diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts index 1116bf892..099c95b25 100644 --- a/tests/boundary/filesystem/cliJsonInput.test.ts +++ b/tests/boundary/filesystem/cliJsonInput.test.ts @@ -1,21 +1,13 @@ import { execFile } from "node:child_process"; -import { constants as bufferConstants } from "node:buffer"; -import { - appendFile, - chmod, - open, - symlink, - type FileHandle, - writeFile, -} from "node:fs/promises"; +import { chmod, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it, onTestFinished } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { isCliOperationFailure } from "../../../src/cliLogging.js"; import { parseCliJsonInput } from "../../../src/cliJsonInput.js"; +import { readCliJsonFile } from "../../../src/cliJsonFile.js"; import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js"; import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -107,58 +99,106 @@ describe("CLI JSON file selection", () => { ); }); -describe("CLI JSON input", () => { - it("reports a valid file beyond the runtime string limit as too large", async () => { - const root = await createTestTempDirectory("rea-json-input-too-large-"); +describe("CLI JSON streamed input", () => { + it("preserves native JSON meanings through chunked file parsing", async () => { + const root = await createTestTempDirectory("rea-json-input-chunks-"); const path = join(root, "input.json"); - const size = bufferConstants.MAX_STRING_LENGTH + 1; - await writeValidOversizedObject(path, size); + const documents = [ + "null", + "false", + "-0", + "1e400", + '{"__proto__":{"observed":true},"constructor":2,"duplicate":1,"duplicate":3}', + JSON.stringify({ + text: `${"x".repeat(65_524)}😀漢字`, + escaped: "\ud800", + }), + JSON.stringify({ [`${"x".repeat(70_000)}😀`]: "long key" }), + JSON.stringify( + Array.from({ length: 4_000 }, (_, id) => ({ id, text: "å" })), + ), + ]; + for (const text of documents) { + await writeFile(path, `${" ".repeat(9 * 1024 * 1024)}${text}`); + const parsed = await parseCliJsonInput(path, "test-input"); + if (!parsed.ok) throw new Error(JSON.stringify(parsed.error)); + expect(parsed.value).toEqual(JSON.parse(text)); + if (text.includes("__proto__")) { + if (typeof parsed.value !== "object" || parsed.value === null) + throw new Error("Expected the parsed object"); + expect(Object.getPrototypeOf(parsed.value)).toBe(Object.prototype); + expect(Object.hasOwn(parsed.value, "__proto__")).toBe(true); + } + } + }); - const result = await parseCliJsonInput(path, "test-input"); - if (result.ok) throw new Error("Expected oversized JSON to be rejected"); - expect(analysisCliErrorEnvelopeSchema.parse(result.error)).toEqual( - result.error, - ); - expect(result).toMatchObject({ - ok: false, - error: { - code: "resource_constraint", - input_path: path, - input_reason: "too-large", - details: { - resource: "memory", - reported_limits: { - boundary: "cli-json-input", - max_string_code_units: bufferConstants.MAX_STRING_LENGTH, - }, + it.each([ + "", + "[1,]", + "{} {}", + '{"value":', + '"unterminated', + "\uFEFF{}", + "\u00a0{}", + "{\u000b}", + "01", + "NaN", + '"\u0001"', + ])("rejects strict JSON syntax violations in files (%j)", async (text) => { + const root = await createTestTempDirectory("rea-json-input-invalid-"); + const path = join(root, "input.json"); + for (const prefix of ["", " ".repeat(9 * 1024 * 1024)]) { + await writeFile(path, `${prefix}${text}`); + expect(await parseCliJsonInput(path, "test-input")).toMatchObject({ + ok: false, + error: { + code: "invalid_request", + input_path: path, + input_reason: "invalid-json", }, - remediation: { - action: expect.stringContaining("re-analyze a smaller selection"), + }); + } + }); + + it.each([Buffer.from([0xf0, 0x28, 0x8c, 0xbc]), Buffer.from([0xe2, 0x82])])( + "rejects malformed and incomplete UTF-8 at a read boundary (%j)", + async (invalid) => { + const root = await createTestTempDirectory("rea-json-input-utf8-"); + const path = join(root, "input.json"); + await writeFile( + path, + Buffer.concat([ + Buffer.from(`${" ".repeat(9 * 1024 * 1024)}"${"x".repeat(65_534)}`), + invalid, + ]), + ); + expect(await parseCliJsonInput(path, "test-input")).toMatchObject({ + ok: false, + error: { + input_reason: "invalid-json", + details: { issues: [{ message: "JSON input is not valid UTF-8" }] }, }, - }, + }); + }, + ); + + it("cancels a file parse and allows a following read", async () => { + const root = await createTestTempDirectory("rea-json-input-cancel-"); + const path = join(root, "input.json"); + await writeFile(path, `${" ".repeat(9 * 1024 * 1024)}{"after":true}`); + const controller = new AbortController(); + const cancelled = readCliJsonFile(path, "test-input", controller.signal); + setImmediate(() => controller.abort(new Error("cancel JSON file parse"))); + await expect(cancelled).rejects.toThrow("cancel JSON file parse"); + await writeFile(path, '{"after":true}'); + expect(await readCliJsonFile(path, "test-input")).toEqual({ + ok: true, + value: { after: true }, }); + }); +}); - expect(isCliOperationFailure(result.error)).toBe(true); - - const characterCount = - Math.floor(bufferConstants.MAX_STRING_LENGTH / 2) + 2; - await writeValidMultibyteString(path, characterCount); - - const multibyteResult = await parseCliJsonInput(path, "test-input"); - if (!multibyteResult.ok) - throw new Error("Expected large multibyte JSON to fit the string limit"); - if (typeof multibyteResult.value !== "string") - throw new Error("Expected parsed JSON string"); - expect(multibyteResult.value.length).toBe(characterCount); - - // Large-input streaming must flush and reject an incomplete UTF-8 suffix. - await appendFile(path, Buffer.from([0xc3])); - expect(await parseCliJsonInput(path, "test-input")).toMatchObject({ - ok: false, - error: { input_path: path, input_reason: "invalid-json" }, - }); - }, 20_000); - +describe("CLI JSON input", () => { it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => { expect(await parseCliJsonInput("[", "test-input")).toMatchObject({ ok: false, @@ -251,47 +291,3 @@ describe("CLI JSON input", () => { }, ); }); - -const writeRepeatedBytes = async ( - handle: FileHandle, - bytes: Buffer, - length: number, -): Promise => { - let remaining = length; - while (remaining > 0) { - const chunkLength = Math.min(bytes.length, remaining); - await handle.writeFile(bytes.subarray(0, chunkLength)); - remaining -= chunkLength; - } -}; - -const writeValidOversizedObject = async ( - path: string, - size: number, -): Promise => { - const handle = await open(path, "w"); - const whitespace = Buffer.alloc(1024 * 1024, 0x20); - try { - await handle.writeFile("{"); - await writeRepeatedBytes(handle, whitespace, size - 2); - await handle.writeFile("}"); - } finally { - await handle.close(); - } -}; - -const writeValidMultibyteString = async ( - path: string, - characterCount: number, -): Promise => { - const encodedCharacters = Buffer.from("é".repeat(512 * 1024)); - const byteLength = characterCount * 2 + 2; - const handle = await open(path, "w"); - try { - await handle.writeFile('"'); - await writeRepeatedBytes(handle, encodedCharacters, byteLength - 2); - await handle.writeFile('"'); - } finally { - await handle.close(); - } -}; From 53ed942a85f51ff9f0e4f01cbb53359df476071d Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:11:38 +0800 Subject: [PATCH 093/189] fix(mcp): preserve JavaScript workflow identity validation (#1366) Preserve canonical distinct-source and unique-native-observation refinements after resolving inline or retained JavaScript workflow inputs. The shared application entry points now return structured invalid_request errors before graph parsing and computation, avoiding another complete graph capture. Six focused tests, actual compiled CLI/SDK stdio workflows, JSON Schema dialect checks, static/document checks, and a real Notion ASAR analysis/recovery/trace/close workflow passed. All 20 final-head checks, including real JavaScript recovery, passed. Native-provider acceptance is not claimed for this provider-neutral validation change. Fixes #1364 Refs #1065 --- .../JavaScriptApplicationWorkflowService.ts | 35 +- ...riptApplicationVersionComparisonSchemas.ts | 67 ++-- .../javascriptExportShapeComparisonSchemas.ts | 35 +- .../javascriptFeatureTraceSchemas.ts | 33 +- .../cli/workflowInputIdentities.test.ts | 318 ++++++++++++++++++ 5 files changed, 444 insertions(+), 44 deletions(-) create mode 100644 tests/boundary/cli/workflowInputIdentities.test.ts diff --git a/src/application/javascript/JavaScriptApplicationWorkflowService.ts b/src/application/javascript/JavaScriptApplicationWorkflowService.ts index f85330cee..cdee1f893 100644 --- a/src/application/javascript/JavaScriptApplicationWorkflowService.ts +++ b/src/application/javascript/JavaScriptApplicationWorkflowService.ts @@ -1,18 +1,24 @@ import { z } from "zod"; -import { - AnalysisInputError, - AnalysisProtocolError, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisProtocolError } from "../../domain/analysisErrorCore.js"; import { type AnalysisError } from "../../domain/analysisErrorBase.js"; import type { Evidence } from "../../domain/evidence.js"; import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; import { compareJavaScriptApplicationVersions } from "../../domain/javascript/javascriptApplicationVersionComparison.js"; -import { compareApplicationVersionsInputSchema } from "../../domain/javascript/javascriptApplicationVersionComparisonSchemas.js"; +import { + compareApplicationVersionsInputSchema, + applicationVersionIdentitiesSchema, +} from "../../domain/javascript/javascriptApplicationVersionComparisonSchemas.js"; import { compareJavaScriptExportShapes } from "../../domain/javascript/javascriptExportShapeComparison.js"; -import { compareJavaScriptExportShapesInputSchema } from "../../domain/javascript/javascriptExportShapeComparisonSchemas.js"; +import { + compareJavaScriptExportShapesInputSchema, + javaScriptExportShapeIdentitiesSchema, +} from "../../domain/javascript/javascriptExportShapeComparisonSchemas.js"; import { traceApplicationFeature } from "../../domain/javascript/javascriptFeatureTrace.js"; -import { traceApplicationFeatureInputSchema } from "../../domain/javascript/javascriptFeatureTraceSchemas.js"; +import { + traceApplicationFeatureInputSchema, + applicationTraceIdentitiesSchema, +} from "../../domain/javascript/javascriptFeatureTraceSchemas.js"; import { err, ok, type Result } from "../../domain/result.js"; import { compareSourceToBundle } from "../../domain/javascript/sourceToBundleComparison.js"; import { compareSourceToBundleInputSchema } from "../../domain/javascript/sourceToBundleComparisonSchemas.js"; @@ -46,6 +52,11 @@ export const traceApplicationFeatureEvidenceValidated = ( input: z.output, ): Result => { const operation = "trace_application_feature"; + const identities = applicationTraceIdentitiesSchema.safeParse(input); + if (!identities.success) + return err( + analysisInputErrorFromIssues(operation, identities.error.issues, input), + ); const sourceResult = parseApplicationGraphEvidence(input.application, [ "application", ]); @@ -105,6 +116,11 @@ export const compareApplicationVersionsEvidenceValidated = ( input: z.output, ): Result => { const operation = "compare_application_versions"; + const identities = applicationVersionIdentitiesSchema.safeParse(input); + if (!identities.success) + return err( + analysisInputErrorFromIssues(operation, identities.error.issues, input), + ); const leftResult = parseApplicationGraphEvidence(input.left, ["left"]); if (!leftResult.ok) return err(applicationGraphEvidenceInputError(operation, leftResult.error)); @@ -223,6 +239,11 @@ export const compareJavaScriptExportShapesEvidenceValidated = ( input: z.output, ): Result => { const operation = "compare_javascript_export_shapes"; + const identities = javaScriptExportShapeIdentitiesSchema.safeParse(input); + if (!identities.success) + return err( + analysisInputErrorFromIssues(operation, identities.error.issues, input), + ); const leftResult = parseApplicationGraphEvidence(input.left, ["left"]); if (!leftResult.ok) return err(applicationGraphEvidenceInputError(operation, leftResult.error)); diff --git a/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts b/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts index e30c74205..309c95c89 100644 --- a/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts +++ b/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts @@ -10,6 +10,52 @@ const evidenceIdSchema = prefixedDigestSchema("ev"); const nodeIdSchema = prefixedDigestSchema("jag_node"); const textSchema = z.string().min(1); +/** Check paired version identities and per-side native identity uniqueness. */ +const validateApplicationVersionIdentities = ( + input: { + readonly left: { readonly evidence_id: string }; + readonly right: { readonly evidence_id: string }; + readonly left_native_observations: readonly { + readonly evidence_id: string; + }[]; + readonly right_native_observations: readonly { + readonly evidence_id: string; + }[]; + }, + context: z.RefinementCtx, +): void => { + if (input.left.evidence_id === input.right.evidence_id) + context.addIssue({ + code: "custom", + path: ["right"], + message: "Application version Evidence must be distinct", + }); + for (const side of [ + "left_native_observations", + "right_native_observations", + ] as const) { + const ids = input[side].map(({ evidence_id: id }) => id); + if (new Set(ids).size !== ids.length) + context.addIssue({ + code: "custom", + path: [side], + message: "Native observations must be unique on each side", + }); + } +}; + +const evidenceIdentitySchema = z.object({ evidence_id: evidenceIdSchema }); + +/** Validate paired version identities without capturing whole analysis graphs. */ +export const applicationVersionIdentitiesSchema = z + .object({ + left: evidenceIdentitySchema, + right: evidenceIdentitySchema, + left_native_observations: z.array(evidenceIdentitySchema), + right_native_observations: z.array(evidenceIdentitySchema), + }) + .superRefine(validateApplicationVersionIdentities); + /** Two authenticated application versions and their native observations. */ export const compareApplicationVersionsInputSchema = z .strictObject({ @@ -18,26 +64,7 @@ export const compareApplicationVersionsInputSchema = z left_native_observations: z.array(evidenceSchema).default([]), right_native_observations: z.array(evidenceSchema).default([]), }) - .superRefine((input, context) => { - if (input.left.evidence_id === input.right.evidence_id) - context.addIssue({ - code: "custom", - path: ["right"], - message: "Application version Evidence must be distinct", - }); - for (const side of [ - "left_native_observations", - "right_native_observations", - ] as const) { - const ids = input[side].map(({ evidence_id: id }) => id); - if (new Set(ids).size !== ids.length) - context.addIssue({ - code: "custom", - path: [side], - message: "Native observations must be unique on each side", - }); - } - }); + .superRefine(validateApplicationVersionIdentities); const candidateNodesSchema = z.tuple([nodeIdSchema]).rest(nodeIdSchema); const exactMatchSchema = z.strictObject({ diff --git a/src/domain/javascript/javascriptExportShapeComparisonSchemas.ts b/src/domain/javascript/javascriptExportShapeComparisonSchemas.ts index 808066c4d..5f9425015 100644 --- a/src/domain/javascript/javascriptExportShapeComparisonSchemas.ts +++ b/src/domain/javascript/javascriptExportShapeComparisonSchemas.ts @@ -53,6 +53,32 @@ const sourceRangeSchema = z }); }); +/** Check that export-shape comparisons bind distinct source Evidence. */ +const validateJavaScriptExportShapeIdentities = ( + input: { + readonly left: { readonly evidence_id: string }; + readonly right: { readonly evidence_id: string }; + }, + context: z.RefinementCtx, +): void => { + if (input.left.evidence_id === input.right.evidence_id) + context.addIssue({ + code: "custom", + path: ["right"], + message: "JavaScript export shape Evidence must be distinct", + }); +}; + +const evidenceIdentitySchema = z.object({ evidence_id: evidenceIdSchema }); + +/** Validate export-shape identities without capturing complete source graphs. */ +export const javaScriptExportShapeIdentitiesSchema = z + .object({ + left: evidenceIdentitySchema, + right: evidenceIdentitySchema, + }) + .superRefine(validateJavaScriptExportShapeIdentities); + /** Two authenticated application graphs and exact export selectors. */ export const compareJavaScriptExportShapesInputSchema = z .strictObject({ @@ -63,14 +89,7 @@ export const compareJavaScriptExportShapesInputSchema = z right_module_path: textSchema, right_export_name: textSchema, }) - .superRefine((input, context) => { - if (input.left.evidence_id === input.right.evidence_id) - context.addIssue({ - code: "custom", - path: ["right"], - message: "JavaScript export shape Evidence must be distinct", - }); - }); + .superRefine(validateJavaScriptExportShapeIdentities); const projectedReturnFieldShape = { path: jsonPointerSchema, diff --git a/src/domain/javascript/javascriptFeatureTraceSchemas.ts b/src/domain/javascript/javascriptFeatureTraceSchemas.ts index 517d7c9ad..ee34bad09 100644 --- a/src/domain/javascript/javascriptFeatureTraceSchemas.ts +++ b/src/domain/javascript/javascriptFeatureTraceSchemas.ts @@ -46,6 +46,29 @@ const applicationFeatureSeedSchema = z.union([ }), ]); +/** Check unique native identities before projecting an application trace. */ +const validateApplicationTraceIdentities = ( + input: { + readonly native_observations: readonly { readonly evidence_id: string }[]; + }, + context: z.RefinementCtx, +): void => { + const ids = input.native_observations.map(({ evidence_id: id }) => id); + if (new Set(ids).size !== ids.length) + context.addIssue({ + code: "custom", + path: ["native_observations"], + message: "Native observations must be unique", + }); +}; + +/** Validate native trace identities without capturing their complete Evidence. */ +export const applicationTraceIdentitiesSchema = z + .object({ + native_observations: z.array(z.object({ evidence_id: evidenceIdSchema })), + }) + .superRefine(validateApplicationTraceIdentities); + /** Evidence-backed application graph and feature seed. */ export const traceApplicationFeatureInputSchema = z .strictObject({ @@ -54,15 +77,7 @@ export const traceApplicationFeatureInputSchema = z seed: applicationFeatureSeedSchema, direction: z.enum(["outgoing", "incoming", "both"]).default("both"), }) - .superRefine((input, context) => { - const ids = input.native_observations.map(({ evidence_id: id }) => id); - if (new Set(ids).size !== ids.length) - context.addIssue({ - code: "custom", - path: ["native_observations"], - message: "Native observations must be unique", - }); - }); + .superRefine(validateApplicationTraceIdentities); const seedMatchSchema = z.strictObject({ node_id: nodeIdSchema, diff --git a/tests/boundary/cli/workflowInputIdentities.test.ts b/tests/boundary/cli/workflowInputIdentities.test.ts new file mode 100644 index 000000000..a724e7fea --- /dev/null +++ b/tests/boundary/cli/workflowInputIdentities.test.ts @@ -0,0 +1,318 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { expect, onTestFinished } from "vitest"; + +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest, type TestCli } from "../../support/cli/cliFixture.js"; + +const compareContract = toolContract("compare_application_versions"); +const analyzeContract = toolContract("analyze_javascript_application"); +const expectInputFailure = ( + value: unknown, + path: string, + message: string, +): void => { + expect(value).toMatchObject({ + code: "invalid_request", + details: { + issues: [{ path: [path], message: expect.stringContaining(message) }], + }, + }); +}; +const runJson = async ( + cli: TestCli, + root: string, + command: string, + input: unknown, +) => { + const path = join(root, "request.json"); + await writeFile(path, JSON.stringify(input)); + return cli.run({ + arguments: [command, path, "--json"], + cwd: root, + environment: { REA_LOG_LEVEL: "silent" }, + }); +}; +const connectMcp = async (root: string) => { + const client = new Client({ + name: "application-input-identities", + version: "1", + }); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + cwd: root, + env: { + PATH: process.env.PATH ?? "", + HOME: root, + XDG_CONFIG_HOME: join(root, "config"), + XDG_CACHE_HOME: join(root, "cache"), + REA_LOG_LEVEL: "silent", + }, + }); + onTestFinished(async () => { + try { + await client.close(); + } finally { + await transport.close(); + } + }); + await client.connect(transport); + const tools = new Map( + (await client.listTools()).tools.map((tool) => [tool.name, tool]), + ); + const call = (name: string, arguments_: Record = {}) => { + const definition = tools.get(name); + if (definition === undefined) + throw new Error(`Missing advertised tool ${name}`); + return client.callTool( + { name, arguments: arguments_ }, + { toolDefinition: definition }, + ); + }; + return { client, tools, call }; +}; + +type Application = ReturnType; +type WorkflowContext = { + cli: TestCli; + root: string; + call: Awaited>["call"]; + application: Application; + other: Application; + reference: { kind: string; evidence_id: string }; + otherReference: { kind: string; evidence_id: string }; +}; +const selectors = { + left_module_path: "main.mjs", + left_export_name: "get", + right_module_path: "main.mjs", + right_export_name: "get", +}; +const seed = { kind: "module", value: "main.mjs", match: "contains" }; + +const checkComparisonIdentities = async ({ + cli, + root, + call, + application, + reference, +}: WorkflowContext) => { + for (const [name, command, extra] of [ + ["compare_application_versions", "compare-application-versions", {}], + [ + "compare_javascript_export_shapes", + "compare-javascript-export-shapes", + selectors, + ], + ] as const) { + for (const [a, b] of [ + [application, application], + [reference, reference], + [application, reference], + [reference, application], + ]) { + const response = await call(name, { left: a, right: b, ...extra }); + expect(response.isError).toBe(true); + expectInputFailure( + parseMcpToolError(response).error, + "right", + "Evidence must be distinct", + ); + } + const invalid = await runJson(cli, root, command, { + left: application, + right: application, + ...extra, + }); + expect(invalid.exitCode).toBe(1); + expectInputFailure(invalid.json, "right", "Evidence must be distinct"); + } +}; + +const checkNativeObservationIdentities = async ({ + cli, + root, + call, + application, + other, + reference, + otherReference, +}: WorkflowContext) => { + for (const side of [ + "left_native_observations", + "right_native_observations", + ] as const) { + const input = { + left: application, + right: other, + [side]: [application, application], + }; + const response = await call("compare_application_versions", { + ...input, + left: reference, + right: otherReference, + }); + expect(response.isError).toBe(true); + expectInputFailure( + parseMcpToolError(response).error, + side, + "Native observations must be unique", + ); + const invalid = await runJson( + cli, + root, + "compare-application-versions", + input, + ); + expect(invalid.exitCode).toBe(1); + expectInputFailure( + invalid.json, + side, + "Native observations must be unique", + ); + } + const traceInput = { + application, + seed, + native_observations: [application, application], + }; + const duplicateTrace = await call("trace_application_feature", { + ...traceInput, + application: reference, + }); + expect(duplicateTrace.isError).toBe(true); + expectInputFailure( + parseMcpToolError(duplicateTrace).error, + "native_observations", + "Native observations must be unique", + ); + const invalidTrace = await runJson( + cli, + root, + "trace-application-feature", + traceInput, + ); + expect(invalidTrace.exitCode).toBe(1); + expectInputFailure( + invalidTrace.json, + "native_observations", + "Native observations must be unique", + ); +}; + +cliTest( + "preserves workflow identity validation through CLI and inline, retained and mixed MCP inputs", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-application-input-identities-", + ); + const left = join(root, "left"), + right = join(root, "right"); + await mkdir(left); + await mkdir(right); + await writeFile( + join(left, "main.mjs"), + "export function get() { return { observed: 1 }; }\n", + ); + await writeFile( + join(right, "main.mjs"), + "export function get() { return { observed: 2 }; }\n", + ); + const { client, tools, call } = await connectMcp(root); + const first = await call("analyze_javascript_application", { + input_path: left, + format: "directory", + }); + const second = await call("analyze_javascript_application", { + input_path: right, + format: "directory", + }); + expect(first.isError).not.toBe(true); + expect(second.isError).not.toBe(true); + const application = analyzeContract.outputSchema.parse( + first.structuredContent, + ); + const other = analyzeContract.outputSchema.parse(second.structuredContent); + const reference = { + kind: "retained-evidence", + evidence_id: application.evidence_id, + }; + const otherReference = { + kind: "retained-evidence", + evidence_id: other.evidence_id, + }; + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + for (const name of [ + "compare_application_versions", + "compare_javascript_export_shapes", + "trace_application_feature", + ]) { + const definition = tools.get(name); + if (definition?.outputSchema === undefined) + throw new Error("Missing workflow schema"); + expect(ajv.validateSchema(definition.inputSchema)).toBe(true); + const { $schema, ...outputKeywords } = definition.outputSchema; + expect( + ajv.validateSchema( + $schema === undefined + ? outputKeywords + : { ...outputKeywords, $schema }, + ), + ).toBe(true); + } + const context = { + cli, + root, + call, + application, + other, + reference, + otherReference, + }; + await checkComparisonIdentities(context); + await checkNativeObservationIdentities(context); + const compared = await call("compare_application_versions", { + left: reference, + right: otherReference, + }); + expect(compared.isError).not.toBe(true); + const result = compareContract.outputSchema.parse( + compared.structuredContent, + ); + expect(result.normalized_result.evidence_links).toEqual( + [application.evidence_id, other.evidence_id].sort(), + ); + const cliResult = await runJson(cli, root, "compare-application-versions", { + left: application, + right: other, + }); + expect(cliResult.exitCode, cliResult.stdout).toBe(0); + expect(compareContract.outputSchema.parse(cliResult.json)).toEqual(result); + expect( + ( + await call("compare_javascript_export_shapes", { + left: reference, + right: otherReference, + ...selectors, + }) + ).isError, + ).not.toBe(true); + expect( + ( + await call("trace_application_feature", { + application: reference, + seed, + }) + ).isError, + ).not.toBe(true); + await client.ping(); + expect((await call("close_binary")).isError).not.toBe(true); + await client.ping(); + }, +); From 890bb66b35d5f9f8ee54ff0049bf7dc7b82b2480 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:24 +0800 Subject: [PATCH 094/189] fix(ida): compare admitted document paths consistently --- src/ida/IdaSessionClient.test.ts | 19 +++++++++++++++++++ src/ida/IdaSessionClient.ts | 6 ++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/ida/IdaSessionClient.test.ts b/src/ida/IdaSessionClient.test.ts index 2b6783c1c..f1bb05467 100644 --- a/src/ida/IdaSessionClient.test.ts +++ b/src/ida/IdaSessionClient.test.ts @@ -1,4 +1,5 @@ import { readFile, readdir, rm } from "node:fs/promises"; +import { sep } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { z } from "zod"; import { @@ -111,6 +112,24 @@ describe("headless IDA producer pagination", () => { }); describe("attached IDA observation semantics", () => { + it("accepts a normalized spelling of the bound document path", async () => { + const { target, producer, client } = await fixture(); + const equivalent = + process.platform === "win32" + ? target.path.toLowerCase().replaceAll("\\", "/") + : target.path.split(sep).join(`${sep}.${sep}`); + + const result = await client.execute("list_procedures", { + document: equivalent, + }); + + expect(result.ok).toBe(true); + expect(producer.calls.some(({ name }) => name === "list_functions")).toBe( + true, + ); + await client.close(); + }); + it("rejects an unrelated document before connecting or opening a provider", async () => { const { producer, client } = await fixture(); const result = await client.execute("list_procedures", { diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 5fac9e18e..db6301c0c 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -165,8 +165,10 @@ export class IdaSessionClient implements AnalysisClient { const document = parameters.document; if ( document !== undefined && - document !== this.target.path && - document !== this.target.sourcePath + (typeof document !== "string" || + (!sameIdaHostPath(document, this.target.path) && + (this.target.sourcePath === undefined || + !sameIdaHostPath(document, this.target.sourcePath)))) ) return err( new AnalysisInputError(operation, undefined, [ From 70bad53847b0e14489acee73d204ff645e1adfcd Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:24 +0800 Subject: [PATCH 095/189] fix(native): distinguish symbol definitions from metadata --- src/domain/functionComparison.test.ts | 4 ++- src/domain/functionComparisonNormalization.ts | 3 +- src/domain/swiftSymbolClassification.ts | 6 +++- src/domain/symbolAnalysis.test.ts | 34 +++++++++++++++++++ src/domain/symbolAnalysis.ts | 25 ++++++++++++-- ...4-uses-complete-inventories-inline.test.ts | 18 ++++++++-- 6 files changed, 81 insertions(+), 9 deletions(-) diff --git a/src/domain/functionComparison.test.ts b/src/domain/functionComparison.test.ts index ebc59a6ef..226fbb716 100644 --- a/src/domain/functionComparison.test.ts +++ b/src/domain/functionComparison.test.ts @@ -143,7 +143,7 @@ describe("function comparison normalized identity", () => { }, ); - it.each(["sub_deadbeef", "fcn.00401000"])( + it.each(["sub_deadbeef", "fcn.00401000", "FUN_00401000", "FUN_deadBEEF"])( "keeps %s as an address-derived name", (name) => { const generated = (base: "0x1000" | "0x2000") => @@ -169,6 +169,8 @@ describe("function comparison normalized identity", () => { it.each([ { name: "sub_deallocate", status: "unchanged" }, { name: "sub_deadbeef", status: "unknown" }, + { name: "FUN_00401000", status: "unknown" }, + { name: "FUN_initialize", status: "unchanged" }, ])("preserves the calls dimension for callee $name", ({ name, status }) => { const calling = (base: "0x1000" | "0x2000") => functionDossierSchema.parse({ diff --git a/src/domain/functionComparisonNormalization.ts b/src/domain/functionComparisonNormalization.ts index 5bf43a972..a676e1e49 100644 --- a/src/domain/functionComparisonNormalization.ts +++ b/src/domain/functionComparisonNormalization.ts @@ -182,8 +182,9 @@ export const sorted = (values: readonly unknown[]): readonly unknown[] => .sort((left, right) => compareUnicodeCodePoints(left.json, right.json)) .map(({ value }) => value); +/** Recognize address-derived procedure names without excluding named FUN_ symbols. */ export const isAutoName = (name: string): boolean => - /^(?:sub_[0-9a-f]+|fcn\.[0-9a-f]+)$/iu.test(name); + /^(?:sub_[0-9a-f]+|fcn\.[0-9a-f]+|FUN_[0-9a-f]+)$/iu.test(name); const parseAddress = (value: string): bigint | null => /^0x[0-9a-f]+$/iu.test(value) ? BigInt(value) : null; diff --git a/src/domain/swiftSymbolClassification.ts b/src/domain/swiftSymbolClassification.ts index 4903a97bd..58b9b0d26 100644 --- a/src/domain/swiftSymbolClassification.ts +++ b/src/domain/swiftSymbolClassification.ts @@ -42,7 +42,11 @@ export const classifySwiftSymbol = ( const kind = mangling.charAt(end); const nominal = NOMINAL_CATEGORIES.get(kind); if (nominal === undefined) { - if (kind === "E" && category !== null) category = "extensions"; + // Current swiftc emits protocol descriptors as `…Mp` without + // the nominal `P` marker (e.g. `_$s4main7ScoringMp`). Decode that exact + // suffix; unknown substitution encodings stay unclassified, never guessed. + if (mangling.slice(end) === "Mp") category = "protocols"; + else if (kind === "E" && category !== null) category = "extensions"; break; } category = nominal; diff --git a/src/domain/symbolAnalysis.test.ts b/src/domain/symbolAnalysis.test.ts index f663d4ec2..8ebb7b762 100644 --- a/src/domain/symbolAnalysis.test.ts +++ b/src/domain/symbolAnalysis.test.ts @@ -12,6 +12,7 @@ describe("symbol analysis", () => { { address: "0x1", name: "_OBJC_CLASS_$_App" }, { address: "0x2", name: "_OBJC_CLASS_$_App" }, { address: "0x3", name: "_OBJC_PROTOCOL_$_Delegate" }, + { address: "0x4", name: "__OBJC_PROTOCOL_REFERENCE_$_Delegate" }, { address: "0x4", name: "_OBJC_PROTOCOL_$_Delegate" }, ]; expect(discoverObjcClasses(names, "App")).toMatchObject({ count: 1 }); @@ -36,6 +37,39 @@ describe("symbol analysis", () => { }); }); + it("recognizes fragile Apple Objective-C class records without alias duplication", () => { + // Apple clang -target i386-apple-macosx10.5 + // -fobjc-runtime=macosx-fragile-10.5 emits these local class records. + // The `.objc_class_name_*` absolute symbols alias the same class and are + // deliberately not selected. + const names = [ + { address: "0x1ac", name: "l_OBJC_CLASS_ProbeClass" }, + { address: "0x0", name: ".objc_class_name_ProbeClass" }, + // A class named `NAME_` produces this exact legacy local symbol. + { address: "0x0", name: "l_OBJC_CLASS_NAME_" }, + ]; + expect(discoverObjcClasses(names, "")).toEqual({ + count: 2, + classes: [ + { address: "0x1ac", name: "l_OBJC_CLASS_ProbeClass" }, + { address: "0x0", name: "l_OBJC_CLASS_NAME_" }, + ], + }); + }); + + it("discovers modern Swift protocol descriptors without treating methods as declarations", () => { + // Current swiftc emits `…Mp` descriptors without the nominal `P` marker. + const names = [ + { address: "0xf0", name: "_$s4main7ScoringMp" }, + { address: "0x100", name: "_$s4main7ScoringTL" }, + { address: "0x110", name: "_$s4main7ScoringP5scoreSiyFTq" }, + ]; + expect(discoverObjcProtocols(names)).toEqual({ + count: 1, + protocols: [{ address: "0xf0", name: "_$s4main7ScoringMp" }], + }); + }); + it("categorizes every Swift mangling family and deduplicates names", () => { const result = categorizeSwiftTypes([ { address: "1", name: "_TtCClass" }, diff --git a/src/domain/symbolAnalysis.ts b/src/domain/symbolAnalysis.ts index 9f2e89915..65e0fe8eb 100644 --- a/src/domain/symbolAnalysis.ts +++ b/src/domain/symbolAnalysis.ts @@ -5,6 +5,18 @@ import { type SwiftTypeCategory, } from "./swiftSymbolClassification.js"; +/** Objective-C class definition markers emitted by modern Apple clang. */ +const OBJC_CLASS_MARKER = "OBJC_CLASS_$_" as const; + +/** Local class records emitted by Apple's fragile Objective-C ABI. */ +const LEGACY_OBJC_CLASS_PREFIX = "l_OBJC_CLASS_" as const; + +/** + * Objective-C protocol declaration marker. `PROTOCOL_REFERENCE` slots + * share the substring but are uses, not definitions. + */ +const OBJC_PROTOCOL_MARKER = "OBJC_PROTOCOL_$_" as const; + /** Select and deduplicate Objective-C class labels. */ export const discoverObjcClasses = ( names: readonly AddressedName[], @@ -12,8 +24,11 @@ export const discoverObjcClasses = ( ): JsonValue => { const classes = uniqueByName( names - .filter(({ name }) => - ["OBJC_CLASS", "OBJC_$_CLASS"].some((marker) => name.includes(marker)), + .filter( + ({ name }) => + name.includes(OBJC_CLASS_MARKER) || + (name.startsWith(LEGACY_OBJC_CLASS_PREFIX) && + name.length > LEGACY_OBJC_CLASS_PREFIX.length), ) .filter(({ name }) => pattern.length === 0 || name.includes(pattern)), ); @@ -29,7 +44,11 @@ export const discoverObjcProtocols = ( ): JsonValue => { const protocols = uniqueByName( names.filter( - ({ name }) => name.includes("OBJC_PROTOCOL") || name.includes("_TtP"), + ({ name }) => + name.includes(OBJC_PROTOCOL_MARKER) || + name.includes("_TtP") || + (name.endsWith("Mp") && + classifySwiftSymbol(name)?.category === "protocols"), ), ); return { diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts index a8c9bf464..661f33634 100644 --- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts +++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts @@ -27,8 +27,17 @@ describe("enhanced MCP tools", () => { expect(name).toBe("list_names"); return Promise.resolve( ok([ - { address: "0x1", value: "_OBJC_CLASS_$_First" }, - { address: "0x2", value: "_OBJC_CLASS_$_Last" }, + // Apple clang modern Objective-C ABI `nm` output: the first row + // is a class definition; the remaining rows are method metadata, + // class_ro_t, and a class reference. + { address: "0x70", value: "_OBJC_CLASS_$_ProbeClass" }, + { address: "0x1a8", value: "__OBJC_$_CLASS_METHODS_ProbeClass" }, + { address: "0x230", value: "__OBJC_CLASS_RO_$_ProbeClass" }, + { address: "0x450", value: "_OBJC_CLASSLIST_REFERENCES_$_" }, + { + address: "0x298", + value: "__OBJC_$_CATEGORY_CLASS_METHODS_ProbeClass_$_Category", + }, ]), ); }, @@ -36,7 +45,10 @@ describe("enhanced MCP tools", () => { const result = jsonResult( await client.callTool({ name: "get_objc_classes", arguments: {} }), ); - expect(result).toMatchObject({ count: 2 }); + expect(result).toEqual({ + count: 1, + classes: [{ address: "0x70", name: "_OBJC_CLASS_$_ProbeClass" }], + }); }); it("returns the complete overview inline with exhaustive totals", async () => { From 5751f5caac86c770123ae739a4e4101a72b0989c Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:25 +0800 Subject: [PATCH 096/189] fix(artifacts): preserve archive facts and Unicode path identity --- src/artifacts/apple/KeyedArchiveReader.ts | 148 ++++++++++-------- .../filesystem/keyedArchiveSelection.test.ts | 47 ++++++ 2 files changed, 126 insertions(+), 69 deletions(-) diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index 6d4af226d..729215929 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -25,6 +25,7 @@ import { } from "../../domain/apple/keyedArchive.js"; import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js"; import { ArtifactReaderFailure } from "../ArtifactReader.js"; +import type { ArtifactEntry } from "../ArtifactReader.js"; import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js"; @@ -47,7 +48,10 @@ export const decodeKeyedArchiveBytes = ( const parsed = binary ? { value: parseBinary(bytes), omittedPrototypeKeys: 0 } : parseXmlPropertyList(xmlText ?? ""); - const graph = projectKeyedArchive(normalizePlist(parsed.value), selection); + const { value: plistValue, unknownRealCount } = projectPlistValue( + parsed.value, + ); + const graph = projectKeyedArchive(plistValue, selection); const numbers = createPlistNumberProjection( binary ? binaryPlistNumberLiterals(bytes) @@ -76,17 +80,15 @@ export const decodeKeyedArchiveBytes = ( ...(parsed.omittedPrototypeKeys === 0 ? [] : [omittedPrototypeKeysLimitation(parsed.omittedPrototypeKeys)]), + ...(unknownRealCount === 0 + ? [] + : [ + `${String(unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because JSON evidence cannot preserve NaN vs infinity.`, + ]), ], }; }; -const normalizePlist = (value: unknown): JsonValue => { - const projected = projectPlistValue(value); - if (projected.unknownRealCount > 0) - throw new RangeError("Keyed archive contains a non-finite real"); - return projected.value; -}; - /** * Point to the workflow that reads the selected kind of file on this host. * decode_interface_builder is portable; inspect_plist requires macOS. @@ -126,75 +128,83 @@ export const inspectBundleKeyedArchive = async (input: { ); const reader = new DirectoryArtifactReader(input.bundlePath); try { + // Match inventory spelling while retaining the raw path for I/O and evidence. + const wanted = selected.path.normalize("NFC"); + const matches: ArtifactEntry[] = []; for await (const entry of reader.entries(input.signal)) { - if (entry.path !== selected.path) continue; - if (entry.kind !== "file") - throw archivePathError( - "invalid_value", - `Archive path selects a ${entry.kind}, not a regular file: ${selected.path}`, + if (entry.path.normalize("NFC") !== wanted) continue; + matches.push(entry); + } + if (matches.length > 1) + throw archivePathError( + "invalid_value", + `Archive path matches ${String(matches.length)} Unicode-equivalent bundle entries; selection is ambiguous: ${selected.path}`, + ); + const entry = matches[0]; + if (entry === undefined) + throw archivePathError( + "invalid_value", + `No regular file exists at ${selected.path} in the active app bundle.`, + ); + if (entry.kind !== "file") + throw archivePathError( + "invalid_value", + `Archive path selects a ${entry.kind}, not a regular file: ${selected.path}`, + ); + if ((entry.declaredSize ?? 0) > MAX_BYTES) + throw new ArtifactReaderFailure("limit", "Keyed archive exceeds 64 MiB"); + const stream = await reader.open(entry, input.signal); + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of stream) { + if (input.signal?.aborted) { + stream.destroy(); + throw new ArtifactReaderFailure( + "cancelled", + "Archive inspection cancelled", ); - if ((entry.declaredSize ?? 0) > MAX_BYTES) + } + const bytes = z.instanceof(Buffer).parse(chunk); + size += bytes.length; + if (size > MAX_BYTES) { + stream.destroy(); throw new ArtifactReaderFailure( "limit", "Keyed archive exceeds 64 MiB", ); - const stream = await reader.open(entry, input.signal); - const chunks: Buffer[] = []; - let size = 0; - for await (const chunk of stream) { - if (input.signal?.aborted) { - stream.destroy(); - throw new ArtifactReaderFailure( - "cancelled", - "Archive inspection cancelled", - ); - } - const bytes = z.instanceof(Buffer).parse(chunk); - size += bytes.length; - if (size > MAX_BYTES) { - stream.destroy(); - throw new ArtifactReaderFailure( - "limit", - "Keyed archive exceeds 64 MiB", - ); - } - chunks.push(bytes); - } - const bytes = Buffer.concat(chunks, size); - try { - return keyedArchiveResultSchema.parse({ - target_sha256: input.targetSha256, - archive_path: entry.path, - archive_sha256: createHash("sha256").update(bytes).digest("hex"), - ...decodeKeyedArchiveBytes(bytes, selected), - }); - } catch (cause) { - if (cause instanceof AnalysisInputError) throw cause; - // An intact file of another kind is not a damaged archive. - if (cause instanceof KeyedArchiveKindError) - throw new AnalysisUnsupportedTargetError( - "inspect_keyed_archive", - join(input.bundlePath, entry.path), - cause.message, - { - cause, - remediationAction: keyedArchiveKindRemediation( - cause.kind, - input.platform ?? process.platform, - ), - }, - ); - throw new ArtifactReaderFailure( - cause instanceof RangeError ? "limit" : "format", - `Cannot decode selected Foundation keyed archive: ${cause instanceof Error ? cause.message : String(cause)}`, - { cause }, - ); } + chunks.push(bytes); + } + const bytes = Buffer.concat(chunks, size); + try { + return keyedArchiveResultSchema.parse({ + target_sha256: input.targetSha256, + archive_path: entry.path, + archive_sha256: createHash("sha256").update(bytes).digest("hex"), + ...decodeKeyedArchiveBytes(bytes, selected), + }); + } catch (cause) { + if (cause instanceof AnalysisInputError) throw cause; + // An intact file of another kind is not a damaged archive. + if (cause instanceof KeyedArchiveKindError) + throw new AnalysisUnsupportedTargetError( + "inspect_keyed_archive", + join(input.bundlePath, entry.path), + cause.message, + { + cause, + remediationAction: keyedArchiveKindRemediation( + cause.kind, + input.platform ?? process.platform, + ), + }, + ); + throw new ArtifactReaderFailure( + cause instanceof RangeError ? "limit" : "format", + `Cannot decode selected Foundation keyed archive: ${cause instanceof Error ? cause.message : String(cause)}`, + { cause }, + ); } - throw archivePathError( - "invalid_value", - `No regular file exists at ${selected.path} in the active app bundle.`, - ); } finally { await reader.close(); } diff --git a/tests/boundary/filesystem/keyedArchiveSelection.test.ts b/tests/boundary/filesystem/keyedArchiveSelection.test.ts index b53aedb7a..7b3e54292 100644 --- a/tests/boundary/filesystem/keyedArchiveSelection.test.ts +++ b/tests/boundary/filesystem/keyedArchiveSelection.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -167,6 +168,52 @@ it("keeps a damaged NSKeyedArchiver archive a format failure", async () => { }); }); +it("selects a decomposed bundle path by its normalized spelling and reports the raw identity", async () => { + const root = await bundle(); + const rawPath = `Contents/Resources/Caf\u0065\u0301.plist`; + const bytes = Buffer.from(archive); + await writeFile(join(root, rawPath), bytes); + + const result = await inspect(root, { + path: rawPath.normalize("NFC"), + }); + + expect(result.archive_path).toBe(rawPath); + expect(result.archive_sha256).toBe( + createHash("sha256").update(bytes).digest("hex"), + ); +}); + +it("keeps an archive readable when a non-finite real is an explicit unknown", async () => { + const root = await bundle(); + const bytes = Buffer.from( + build({ + $archiver: "NSKeyedArchiver", + $version: 100000, + $objects: ["$null", Number.NaN], + $top: { root: { CF$UID: 1 } }, + }), + ); + await writeFile( + join(root, "Contents", "Resources", "NonFinite.plist"), + bytes, + ); + + const result = await inspect(root, { + path: "Contents/Resources/NonFinite.plist", + }); + + expect(result.objects).toContainEqual( + expect.objectContaining({ + id: 1, + value: { $plist_type: "real", value: null }, + }), + ); + expect(result.limitations).toContain( + '1 non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because JSON evidence cannot preserve NaN vs infinity.', + ); +}); + const asAnalysisError = (value: unknown): AnalysisError => { if (!(value instanceof AnalysisError)) throw value; return value; From 5aa200285ab066e48b37b716495936e6e2a963fd Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:25 +0800 Subject: [PATCH 097/189] fix(artifacts): infer legacy Mach-O simulator platforms --- src/artifacts/apple/MachoImage.fixture.ts | 15 +++ .../apple/MachoLoadCommandReader.test.ts | 112 ++++++++++++++++++ src/artifacts/apple/MachoLoadCommandReader.ts | 48 +++++++- 3 files changed, 169 insertions(+), 6 deletions(-) diff --git a/src/artifacts/apple/MachoImage.fixture.ts b/src/artifacts/apple/MachoImage.fixture.ts index 1f26921a9..d43249d38 100644 --- a/src/artifacts/apple/MachoImage.fixture.ts +++ b/src/artifacts/apple/MachoImage.fixture.ts @@ -11,9 +11,14 @@ export const LC = { DYLD_ENVIRONMENT: 0x27, CODE_SIGNATURE: 0x1d, BUILD_VERSION: 0x32, + VERSION_MIN_MACOSX: 0x24, + VERSION_MIN_IPHONEOS: 0x25, + VERSION_MIN_TVOS: 0x2f, + VERSION_MIN_WATCHOS: 0x30, } as const; export const CPU = { + i386: { type: 7, subtype: 3 }, arm64: { type: 0x0100000c, subtype: 0 }, arm64e: { type: 0x0100000c, subtype: 0x80000002 }, x86_64: { type: 0x01000007, subtype: 3 }, @@ -86,6 +91,16 @@ export const buildVersionCommand = (platform: number): Uint8Array => { return bytes; }; +/** `version_min_command` carrying `LC_VERSION_MIN_*` semantics. */ +export const versionMinCommand = (command: number): Uint8Array => { + const bytes = new Uint8Array(16); + const view = new DataView(bytes.buffer); + view.setUint32(0, command, true); + view.setUint32(4, bytes.length, true); + view.setUint32(8, 0x00090000, true); + return bytes; +}; + /** A 64-bit (or 32-bit) little-endian Mach-O image made of the given commands. */ export const machoImage = (options: { readonly cpu?: { readonly type: number; readonly subtype: number }; diff --git a/src/artifacts/apple/MachoLoadCommandReader.test.ts b/src/artifacts/apple/MachoLoadCommandReader.test.ts index 4250db968..df26940bf 100644 --- a/src/artifacts/apple/MachoLoadCommandReader.test.ts +++ b/src/artifacts/apple/MachoLoadCommandReader.test.ts @@ -1,3 +1,7 @@ +import { createHash } from "node:crypto"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + import { describe, expect, it } from "vitest"; import { @@ -13,16 +17,124 @@ import { machoImage, readerOf, rpathCommand, + versionMinCommand, } from "./MachoImage.fixture.js"; import { MAX_LOAD_COMMAND_BYTES, hasMachoMagic, readMachoImage, } from "./MachoLoadCommandReader.js"; +import { traceDylibResolution } from "./DylibResolutionReader.js"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; const read = (bytes: Uint8Array) => readMachoImage(readerOf(bytes), bytes.length); +// Legacy `LC_VERSION_MIN_*` commands carry no simulator flag: per dyld +// rules Intel images are simulator, ARM images are device (tvOS simulator +// is x86_64 only). A legacy simulator executable must not fail resolution +// against a modern simulator dylib. +it.each([ + { command: LC.VERSION_MIN_IPHONEOS, cpu: CPU.i386, platform: 7 }, + { command: LC.VERSION_MIN_IPHONEOS, cpu: CPU.x86_64, platform: 7 }, + { command: LC.VERSION_MIN_IPHONEOS, cpu: CPU.arm64, platform: 2 }, + { command: LC.VERSION_MIN_TVOS, cpu: CPU.x86_64, platform: 8 }, + { command: LC.VERSION_MIN_TVOS, cpu: CPU.arm64, platform: 3 }, + { command: LC.VERSION_MIN_WATCHOS, cpu: CPU.i386, platform: 9 }, + { command: LC.VERSION_MIN_WATCHOS, cpu: CPU.arm64, platform: 4 }, + { command: LC.VERSION_MIN_MACOSX, cpu: CPU.x86_64, platform: 1 }, +] as const)( + "classifies legacy command $command on $cpu.type as platform $platform", + async ({ command, cpu, platform }) => { + const facts = await read( + machoImage({ cpu, commands: [versionMinCommand(command)] }), + ); + if (facts.status !== "parsed") throw new Error(facts.status); + expect(facts.slices[0]).toMatchObject({ platform, platforms: [platform] }); + }, +); + +it("uses legacy simulator and device platform facts when resolving dylibs", async () => { + const root = await createTestTempDirectory("rea-macho-legacy-platform-"); + const dylibPath = "Frameworks/libThing.dylib"; + const installName = "@rpath/libThing.dylib"; + const intelExecutable = machoImage({ + cpu: CPU.x86_64, + commands: [ + versionMinCommand(LC.VERSION_MIN_IPHONEOS), + rpathCommand("@executable_path/Frameworks"), + dylibCommand(LC.LOAD_DYLIB, installName), + ], + }); + const armExecutable = machoImage({ + cpu: CPU.arm64, + commands: [ + versionMinCommand(LC.VERSION_MIN_IPHONEOS), + rpathCommand("@executable_path/Frameworks"), + dylibCommand(LC.LOAD_DYLIB, installName), + ], + }); + const simulatorDylib = fatImage([ + { + cpu: CPU.x86_64, + bytes: machoImage({ + cpu: CPU.x86_64, + fileType: FILE_TYPE.dylib, + commands: [ + buildVersionCommand(7), + dylibCommand(LC.ID_DYLIB, installName), + ], + }), + }, + { + cpu: CPU.arm64, + bytes: machoImage({ + cpu: CPU.arm64, + fileType: FILE_TYPE.dylib, + commands: [ + buildVersionCommand(7), + dylibCommand(LC.ID_DYLIB, installName), + ], + }), + }, + ]); + await mkdir(join(root, "Frameworks"), { recursive: true }); + await writeFile(join(root, "Intel"), intelExecutable); + await writeFile(join(root, "Arm"), armExecutable); + await writeFile(join(root, dylibPath), simulatorDylib); + + const trace = async (target: string, architecture: "arm64" | "x86_64") => { + const bytes = target === "Intel" ? intelExecutable : armExecutable; + return traceDylibResolution({ + rootPath: root, + targetPath: join(root, target), + targetSha256: createHash("sha256").update(bytes).digest("hex"), + enumerateRoots: false, + parameters: { roots: [target], architecture }, + }); + }; + const intelTrace = await trace("Intel", "x86_64"); + const armTrace = await trace("Arm", "arm64"); + + expect(intelTrace.edges).toContainEqual( + expect.objectContaining({ + loader: "Intel", + resolution: expect.objectContaining({ + status: "resolved", + image: dylibPath, + }), + }), + ); + expect(armTrace.edges).toContainEqual( + expect.objectContaining({ + loader: "Arm", + candidates: expect.arrayContaining([ + expect.objectContaining({ outcome: "platform-mismatch" }), + ]), + }), + ); +}); + describe("Mach-O load command reader: decodes thin-image load commands", () => { it("decodes dylib loading commands of a thin image", async () => { const image = machoImage({ diff --git a/src/artifacts/apple/MachoLoadCommandReader.ts b/src/artifacts/apple/MachoLoadCommandReader.ts index 6389c5e1b..5a948cb98 100644 --- a/src/artifacts/apple/MachoLoadCommandReader.ts +++ b/src/artifacts/apple/MachoLoadCommandReader.ts @@ -45,6 +45,47 @@ const LC_VERSION_MIN_TVOS = 0x2f; const LC_VERSION_MIN_WATCHOS = 0x30; const LC_BUILD_VERSION = 0x32; +// `mach-o/loader.h` `PLATFORM_*` numbers observed via Apple linker output. +const PLATFORM_MACOS = 1; +const PLATFORM_IOS = 2; +const PLATFORM_TVOS = 3; +const PLATFORM_WATCHOS = 4; +const PLATFORM_IOSSIMULATOR = 7; +const PLATFORM_TVOSSIMULATOR = 8; +const PLATFORM_WATCHOSSIMULATOR = 9; + +const CPU_TYPE_I386 = 7; +const CPU_TYPE_X86_64 = 0x01000007; + +/** + * Legacy `LC_VERSION_MIN_*` commands predate explicit simulator platform + * IDs. Per Apple's dyld rules the image CPU type distinguishes simulator + * from device: Intel images are simulator, ARM images are device + * (tvOS simulator applies to x86_64 only). `LC_BUILD_VERSION` platform + * numbers are preserved verbatim; unknown future numbers stay unknown + * downstream, never mapped to nearest. + */ +const legacyVersionMinPlatform = ( + command: number, + cpuType: number, +): number | undefined => { + const isIntel = cpuType === CPU_TYPE_I386 || cpuType === CPU_TYPE_X86_64; + switch (command) { + case LC_VERSION_MIN_MACOSX: + return PLATFORM_MACOS; + case LC_VERSION_MIN_IPHONEOS: + return isIntel ? PLATFORM_IOSSIMULATOR : PLATFORM_IOS; + case LC_VERSION_MIN_TVOS: + return cpuType === CPU_TYPE_X86_64 + ? PLATFORM_TVOSSIMULATOR + : PLATFORM_TVOS; + case LC_VERSION_MIN_WATCHOS: + return isIntel ? PLATFORM_WATCHOSSIMULATOR : PLATFORM_WATCHOS; + default: + return undefined; + } +}; + /** `mach-o/loader.h` `dylib_use_command`: `nameoff == 28` and this marker. */ const DYLIB_USE_MARKER = 0x1a741800; const DYLIB_USE_WEAK_LINK = 0x1; @@ -377,12 +418,7 @@ const decodeCommand = ( slice.platforms.push(platform); return; } - const legacyPlatform = new Map([ - [LC_VERSION_MIN_MACOSX, 1], - [LC_VERSION_MIN_IPHONEOS, 2], - [LC_VERSION_MIN_TVOS, 3], - [LC_VERSION_MIN_WATCHOS, 4], - ]).get(command); + const legacyPlatform = legacyVersionMinPlatform(command, slice.cpu_type); if (legacyPlatform !== undefined) { if (body.byteLength < 16) throw new MachoFormatIssue( From abf5e243c4d2cae03404b6e1fb1ccc77be917b53 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:26 +0800 Subject: [PATCH 098/189] fix(update): preserve disabled client registrations --- src/application/UpdateMaintenance.ts | 6 ++++-- .../process-global/updateMaintenance.test.ts | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/application/UpdateMaintenance.ts b/src/application/UpdateMaintenance.ts index bc12c9a9a..c0703eefe 100644 --- a/src/application/UpdateMaintenance.ts +++ b/src/application/UpdateMaintenance.ts @@ -7,6 +7,7 @@ import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.j import { readClientRegistrationStatuses } from "./ClientRegistrationStatus.js"; import { clientServerForcedEnabled, + clientServerListedDisabled, effectiveClientServer, parseClientConfiguration, } from "./ClientConfigurationDocument.js"; @@ -77,11 +78,12 @@ export const existingMaintenanceScope = async ( disabled: z.boolean().optional(), }) .parse(effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey)); - // OMP's enabledServers allowlist runs an entry marked `enabled: false`. + // Root disable lists override enabled entries and OMP's force-on allowlist. if ( (enabled.enabled !== false || clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) && - enabled.disabled !== true + enabled.disabled !== true && + !clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey) ) clients.push(client.name); } diff --git a/tests/process-global/updateMaintenance.test.ts b/tests/process-global/updateMaintenance.test.ts index 568629719..bdda28912 100644 --- a/tests/process-global/updateMaintenance.test.ts +++ b/tests/process-global/updateMaintenance.test.ts @@ -100,6 +100,27 @@ describe("OMP integration maintenance", () => { existingMaintenanceScope(home, entryPoint, process.env), ).resolves.toMatchObject({ clients: ["omp"] }); }); + + it("preserves Grok Build disabled_mcp_servers during maintenance planning", async () => { + const registration = `[mcp_servers.rea]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(entryPoint)}, "mcp"]\nstartup_timeout_sec = 30\n`; + const configPath = await writeClient( + "grok_build", + `disabled_mcp_servers = ["rea", "other"]\n${registration}`, + ); + await expect( + existingMaintenanceScope(home, entryPoint, process.env), + ).resolves.toMatchObject({ clients: [] }); + expect(await readFile(configPath, "utf8")).toContain( + 'disabled_mcp_servers = ["rea", "other"]', + ); + await writeFile( + configPath, + `disabled_mcp_servers = ["other"]\n${registration}`, + ); + await expect( + existingMaintenanceScope(home, entryPoint, process.env), + ).resolves.toMatchObject({ clients: ["grok_build"] }); + }); }); describe("existing REA integration maintenance", () => { From 617cd84d27d100e7cc3cd4b5721dea4a996c9775 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:26 +0800 Subject: [PATCH 099/189] fix(browser): retain malformed redirect diagnostics --- src/browser/WebSourceMapFetcher.ts | 23 ++++++++--- ...cdpBrowserProvider.document_script.test.ts | 1 + .../browser/webSourceMapHttpStatus.test.ts | 38 +++++++++++++++++++ 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index 546fd9d97..3c2d3ae81 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -180,6 +180,15 @@ class SourceMapEncodingError extends Error { } } +class SourceMapRedirectLocationError extends Error { + constructor(url: string, location: string) { + super( + `Source-map redirect from ${JSON.stringify(url)} supplied an invalid Location URL: ${JSON.stringify(location)}.`, + ); + this.name = "SourceMapRedirectLocationError"; + } +} + const fetchOne = async ( request: WebSourceMapRequest, input: AnalyzeWebBundleInput, @@ -250,11 +259,11 @@ const fetchOne = async ( return emptySourceMapItem( request, "fetch_failed", - cause instanceof SourceMapSizeLimitError + cause instanceof SourceMapRedirectLocationError || + cause instanceof SourceMapSizeLimitError || + cause instanceof SourceMapDeadlineError ? cause.message - : cause instanceof SourceMapDeadlineError - ? cause.message - : "Source-map fetch or validation failed.", + : "Source-map fetch or validation failed.", ); } }; @@ -296,7 +305,11 @@ const fetchFollowingApprovedRedirects = async ( const location = response.headers.get("location"); if (location === null) return { response, fetchedUrl: current }; await response.body?.cancel(); - current = new URL(location, current).href; + try { + current = new URL(location, current).href; + } catch { + throw new SourceMapRedirectLocationError(current, location); + } } }; diff --git a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts index 9a859f034..7131b30d8 100644 --- a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts @@ -143,6 +143,7 @@ describe("CdpBrowserProvider: approved accessibility and source capture", () => items: [ { status: "included", + declared_url: `${browser.allowedOrigin}/app.js.map?token=map-secret`, original_sources: [ expect.objectContaining({ source: `${browser.allowedOrigin}/src/main.ts`, diff --git a/tests/boundary/browser/webSourceMapHttpStatus.test.ts b/tests/boundary/browser/webSourceMapHttpStatus.test.ts index 69763ddf9..f07419968 100644 --- a/tests/boundary/browser/webSourceMapHttpStatus.test.ts +++ b/tests/boundary/browser/webSourceMapHttpStatus.test.ts @@ -85,3 +85,41 @@ it.each([ } }, ); + +it("keeps the declared URL and reports malformed redirect Location evidence", async () => { + const declaredUrl = "https://app.example.test/declared.map"; + const input = analyzeWebBundleInputSchema.parse({ + cdp_endpoint: "http://127.0.0.1:9222", + target_id: "selected-page", + allowed_origins: ["https://app.example.test"], + fetch_source_maps: true, + }); + const result = await fetchWebSourceMaps( + [ + { + scriptKey: `scr_${"1".repeat(64)}`, + declaredUrl, + fetchUrl: declaredUrl, + }, + ], + input, + undefined, + { + fetch: () => + Promise.resolve( + new Response(null, { + status: 302, + headers: { location: "http://[invalid" }, + }), + ), + }, + ); + + expect(result.items[0]).toMatchObject({ + status: "fetch_failed", + declared_url: declaredUrl, + limitation: expect.stringContaining("invalid Location URL"), + }); + expect(result.items[0]?.limitation).toContain(declaredUrl); + expect(result.items[0]?.limitation).toContain("http://[invalid"); +}); From 0f10499245ec2fab8823f116caf34450b3a7385b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:27 +0800 Subject: [PATCH 100/189] refactor(javascript): share Babel child traversal --- .../javascript/javascriptSemanticReturns.ts | 14 ++----- .../javascript/javascriptSemanticTraversal.ts | 3 +- src/domain/referenceSourceImportParsing.ts | 42 ++++--------------- 3 files changed, 13 insertions(+), 46 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts index 95228ea3e..15b698a02 100644 --- a/src/domain/javascript/javascriptSemanticReturns.ts +++ b/src/domain/javascript/javascriptSemanticReturns.ts @@ -26,7 +26,10 @@ import { import { evaluateSemanticExpression } from "./javascriptSemanticValues.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; import { semanticReturnCoverage } from "./javascriptSemanticCoverage.js"; -import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; +import { + childNodes, + traverseJavaScriptAst, +} from "./javascriptSemanticTraversal.js"; interface ReturnExpression { readonly node: t.Node | null; @@ -145,15 +148,6 @@ const directReturnExpressions = (callable: t.Node): ReturnExpression[] => { return output; }; -const childNodes = (node: t.Node): t.Node[] => - (t.VISITOR_KEYS[node.type] ?? []).flatMap((key) => { - const value: unknown = Reflect.get(node, key); - if (t.isNode(value)) return [value]; - return Array.isArray(value) - ? value.filter((item): item is t.Node => t.isNode(item)) - : []; - }); - const callableIdsForBinding = ( binding: JavaScriptSemanticBindingState, state: JavaScriptSemanticAnalysisState, diff --git a/src/domain/javascript/javascriptSemanticTraversal.ts b/src/domain/javascript/javascriptSemanticTraversal.ts index 5eb311ac2..4719ce34d 100644 --- a/src/domain/javascript/javascriptSemanticTraversal.ts +++ b/src/domain/javascript/javascriptSemanticTraversal.ts @@ -50,7 +50,8 @@ interface TraversalFrame { nextIndex: number; } -const childNodes = (node: t.Node): t.Node[] => { +/** Return child Babel nodes in visitor-key order. */ +export const childNodes = (node: t.Node): t.Node[] => { const keys = t.VISITOR_KEYS[node.type]; if (keys === undefined) return []; const children: t.Node[] = []; diff --git a/src/domain/referenceSourceImportParsing.ts b/src/domain/referenceSourceImportParsing.ts index 1abfc6a51..3e0832ee4 100644 --- a/src/domain/referenceSourceImportParsing.ts +++ b/src/domain/referenceSourceImportParsing.ts @@ -6,6 +6,7 @@ import type { Node, StringLiteral, } from "@babel/types"; +import { traverseJavaScriptAst } from "./javascript/javascriptSemanticTraversal.js"; import { isCallExpression, isExportAllDeclaration, @@ -15,7 +16,6 @@ import { isImportDeclaration, isImportExpression, isMemberExpression, - isNode, isStringLiteral, isTSExternalModuleReference, isTSImportEqualsDeclaration, @@ -201,39 +201,6 @@ const isRequireCallee = (callee: Node | null | undefined): boolean => { return false; }; -const collectModuleExpressions = ( - node: unknown, - targets: Array, -): void => { - if (node === null || node === undefined) return; - if (typeof node !== "object") return; - if (Array.isArray(node)) { - for (const item of node) collectModuleExpressions(item, targets); - return; - } - if (!isNode(node)) return; - if (isCallExpression(node) || isImportExpression(node)) { - targets.push(node); - } - for (const value of Object.values(node)) { - if ( - value !== null && - value !== undefined && - typeof value === "object" && - !isSourceLocation(value) - ) { - collectModuleExpressions(value, targets); - } - } -}; - -const isSourceLocation = (value: unknown): boolean => - typeof value === "object" && - value !== null && - "start" in value && - "end" in value && - !("type" in value); - const extractRequireAndDynamicImports = ( body: readonly Node[], from_path: string, @@ -241,7 +208,12 @@ const extractRequireAndDynamicImports = ( ): void => { const expressions: Array = []; for (const statement of body) - collectModuleExpressions(statement, expressions); + traverseJavaScriptAst(statement, { + enter: (node) => { + if (isCallExpression(node) || isImportExpression(node)) + expressions.push(node); + }, + }); for (const call of expressions) { if (isImportExpression(call)) { From 614fb7681ee9e4eba7219c1ee9e90d6a85d78095 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:58:27 +0800 Subject: [PATCH 101/189] fix(evidence): order canonical projections independently of locale --- ...econstructionObligationLedgerProjection.ts | 6 ++++- .../binary/AnalysisSnapshotCache.ts | 14 +++++++---- src/domain/analysisSnapshot.ts | 7 +++++- src/domain/browserCompleteness.ts | 6 +++-- src/domain/callPath.ts | 13 ++++------- src/domain/canonicalDigest.test.ts | 15 ++++++------ src/domain/changedBehavior.ts | 13 ++++++----- src/domain/evidenceBundle.ts | 8 ++++--- src/domain/functionComparison.ts | 3 ++- src/domain/functionDossierEvidence.ts | 3 ++- .../javascript/sourceToBundleSignals.ts | 10 ++++---- src/domain/jsonShape.test.ts | 12 ++++------ src/domain/jsonShape.ts | 6 +---- src/domain/native/objcSwiftMetadata.ts | 7 +++--- src/domain/reconstructionCoverage.ts | 7 +++--- src/domain/reconstructionUnknowns.ts | 12 +++++----- src/domain/reconstructionVerification.ts | 7 ++++-- src/domain/residualUnknown.ts | 11 +++++---- src/domain/staticRuntimeCorrelation.ts | 3 ++- src/domain/webCaptureDiff.ts | 12 +++++++--- src/domain/webInventory.ts | 6 +++-- .../mcp/browserComparisonInput.test.ts | 23 +++++++++++++++---- 22 files changed, 123 insertions(+), 81 deletions(-) diff --git a/src/application/ReconstructionObligationLedgerProjection.ts b/src/application/ReconstructionObligationLedgerProjection.ts index 89c6d6585..f77a6c9d1 100644 --- a/src/application/ReconstructionObligationLedgerProjection.ts +++ b/src/application/ReconstructionObligationLedgerProjection.ts @@ -2,6 +2,9 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; +import { canonicalJson } from "../domain/comparisonSemantics.js"; +import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; + import type { ReconstructionObligation, ReconstructionObligationLedger, @@ -118,7 +121,8 @@ export const obligationLedgerStatus = ( export const obligationEdgeOrder = ( left: { readonly obligation_id: string }, right: { readonly obligation_id: string }, -): number => JSON.stringify(left).localeCompare(JSON.stringify(right)); +): number => + compareUnicodeCodePoints(canonicalJson(left), canonicalJson(right)); export const digestObligationLedgerValue = (value: unknown): string => { const encoded = canonicalize(value); diff --git a/src/application/binary/AnalysisSnapshotCache.ts b/src/application/binary/AnalysisSnapshotCache.ts index 81f73bcc0..7d807065c 100644 --- a/src/application/binary/AnalysisSnapshotCache.ts +++ b/src/application/binary/AnalysisSnapshotCache.ts @@ -30,6 +30,7 @@ import type { CapabilityDescriptor, } from "../AnalysisProvider.js"; import { OFFICIAL_TOOL_CONTRACTS } from "../../contracts/officialToolContracts.js"; +import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; const STATEFUL_OPERATIONS: ReadonlySet = new Set([ "health", @@ -144,10 +145,11 @@ export class AnalysisSnapshotCache { const snapshotTargetIdentity = snapshotTarget(target); const binding = snapshotBinding(profile); const entries = [...this.#entries.values()].sort((left, right) => - left.query_id.localeCompare(right.query_id), + compareUnicodeCodePoints(left.query_id, right.query_id), ); const workflows = [...this.#workflowEntries.values()].sort( - (left, right) => left.query_id.localeCompare(right.query_id), + (left, right) => + compareUnicodeCodePoints(left.query_id, right.query_id), ); // Parsing owns the returned JSON and metadata; pre-cloning the same // payloads here only adds another full materialization. @@ -209,14 +211,18 @@ export class AnalysisSnapshotCache { /** Return canonical entries for persistence. */ entries(): AnalysisSnapshotEntry[] { return [...this.#entries.values()] - .sort((left, right) => left.query_id.localeCompare(right.query_id)) + .sort((left, right) => + compareUnicodeCodePoints(left.query_id, right.query_id), + ) .map((entry) => structuredClone(entry)); } /** Return canonical composed-workflow entries for persistence. */ workflowEntries(): AnalysisSnapshotWorkflowEntry[] { return [...this.#workflowEntries.values()] - .sort((left, right) => left.query_id.localeCompare(right.query_id)) + .sort((left, right) => + compareUnicodeCodePoints(left.query_id, right.query_id), + ) .map((entry) => structuredClone(entry)); } diff --git a/src/domain/analysisSnapshot.ts b/src/domain/analysisSnapshot.ts index 2c9156dca..1da8db11d 100644 --- a/src/domain/analysisSnapshot.ts +++ b/src/domain/analysisSnapshot.ts @@ -3,6 +3,8 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + import { analysisProfileSchema, analysisProfilesEqual, @@ -463,7 +465,10 @@ const hasCanonicalQueryOrder = ( ): boolean => { let previous: string | undefined; for (const { query_id: queryId } of entries) { - if (previous !== undefined && previous.localeCompare(queryId) > 0) + if ( + previous !== undefined && + compareUnicodeCodePoints(previous, queryId) > 0 + ) return false; previous = queryId; } diff --git a/src/domain/browserCompleteness.ts b/src/domain/browserCompleteness.ts index 64cca6b13..6ee03e375 100644 --- a/src/domain/browserCompleteness.ts +++ b/src/domain/browserCompleteness.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + /** Stable browser sections used by coverage and omission accounting. */ const browserSectionSchema = z.enum([ "frames", @@ -138,6 +140,6 @@ const canonicalExclusions = ( ): BrowserExclusion[] => [...exclusions].sort( (left, right) => - left.section.localeCompare(right.section) || - left.reason.localeCompare(right.reason), + compareUnicodeCodePoints(left.section, right.section) || + compareUnicodeCodePoints(left.reason, right.reason), ); diff --git a/src/domain/callPath.ts b/src/domain/callPath.ts index bc833828f..e468ba0ec 100644 --- a/src/domain/callPath.ts +++ b/src/domain/callPath.ts @@ -10,6 +10,7 @@ import { parseFunctionEvidence, type FunctionSnapshot, } from "./functionDossierEvidence.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; /** Minimal directed caller-to-callee adjacency for call-path search. */ class CallGraph { @@ -104,9 +105,7 @@ export const buildCallPath = (input: CallPathInput): CallPathResult => { goal: parsed.goal.address, explored: summarizeSearch(graph, search.reached), evidence_links: uniqueEvidence(snapshots.values()), - limitations: [...new Set(limitations)].sort((left, right) => - left.localeCompare(right), - ), + limitations: [...new Set(limitations)].sort(compareUnicodeCodePoints), }; const searchScope = { exhaustive }; if (found) @@ -242,9 +241,7 @@ const inspectSearch = ({ ); continue; } - const neighbors = graph - .outNeighbors(node) - .sort((left, right) => left.localeCompare(right)); + const neighbors = graph.outNeighbors(node).sort(compareUnicodeCodePoints); for (const neighbor of neighbors) if (!reached.has(neighbor)) { reached.set(neighbor, depth + 1); @@ -289,7 +286,7 @@ const enumeratePaths = ({ distance !== undefined && goalDistances.get(neighbor) === distance - 1, ) - .sort((left, right) => left.localeCompare(right)); + .sort(compareUnicodeCodePoints); neighbors.set(node, candidates); } return { neighbors: candidates, nextIndex: 0 }; @@ -370,4 +367,4 @@ const snapshotLinks = (snapshot: FunctionSnapshot | undefined): string[] => { const uniqueEvidence = (snapshots: Iterable): string[] => [ ...new Set([...snapshots].flatMap((snapshot) => snapshotLinks(snapshot))), - ].sort((left, right) => left.localeCompare(right)); + ].sort(compareUnicodeCodePoints); diff --git a/src/domain/canonicalDigest.test.ts b/src/domain/canonicalDigest.test.ts index 51df94619..6a18a2ad0 100644 --- a/src/domain/canonicalDigest.test.ts +++ b/src/domain/canonicalDigest.test.ts @@ -6,7 +6,7 @@ import { describe, expect } from "vitest"; import { digestCanonicalValue } from "./canonicalDigest.js"; -const legacyDigest = (value: unknown): string => { +const canonicalizeDigest = (value: unknown): string => { const encoded = canonicalize(value); if (encoded === undefined) throw new TypeError("Unserializable fixture"); return createHash("sha256").update(encoded).digest("hex"); @@ -16,7 +16,7 @@ describe("incremental canonical digest", () => { it.prop([fc.jsonValue()])( "preserves canonicalize digests for JSON values", (value) => { - expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); + expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); }, ); @@ -25,6 +25,7 @@ describe("incremental canonical digest", () => { const sparse: unknown[] = [undefined, Symbol("omit"), () => undefined]; sparse.length = 6; const fixtures: unknown[] = [ + { "\ue000": "bmp", 𐀀: "supplementary" }, { "€": "\ud800", "😀": "\udc00", @@ -40,7 +41,7 @@ describe("incremental canonical digest", () => { { nested: { toJSON: () => undefined } }, ]; for (const value of fixtures) - expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); + expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); }); it("rejects unsupported roots, non-finite numbers, BigInt and ancestor cycles", () => { @@ -59,14 +60,14 @@ describe("incremental canonical digest", () => { const value = { payload: Array.from({ length: 64 }, () => "x".repeat(16_384)), }; - expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); + expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); }); it("keeps digests identical when buffered parts cross flush boundaries", () => { const manyKeys: Record = {}; for (let i = 0; i < 2000; i += 1) manyKeys[`k${i}`] = i; const value = { keys: manyKeys, tail: ["€", "😀", "x".repeat(9000)] }; - expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); + expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); }); it("preserves canonicalize property access and toJSON cycle behavior", () => { @@ -80,11 +81,11 @@ describe("incremental canonical digest", () => { }; }; expect(digestCanonicalValue(createAccessor())).toBe( - legacyDigest(createAccessor()), + canonicalizeDigest(createAccessor()), ); const shared = { toJSON: () => ({ answer: 42 }) }; expect(digestCanonicalValue([shared, shared])).toBe( - legacyDigest([shared, shared]), + canonicalizeDigest([shared, shared]), ); }); }); diff --git a/src/domain/changedBehavior.ts b/src/domain/changedBehavior.ts index 3e1079fad..bd14cee31 100644 --- a/src/domain/changedBehavior.ts +++ b/src/domain/changedBehavior.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { artifactComparisonResultSchema } from "./artifactComparison.js"; import { uniqueSorted } from "./canonicalOrdering.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { comparisonSourceEvidenceIds } from "./comparisonSourceEvidence.js"; import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js"; import { functionComparisonResultSchema } from "./functionComparisonSchemas.js"; @@ -388,12 +389,12 @@ const count = ( .length; const compareFindings = (left: Finding, right: Finding): number => - [left.scope, left.dimension, left.source_comparison_id] - .join("\0") - .localeCompare( - [right.scope, right.dimension, right.source_comparison_id].join("\0"), - "en", - ); + compareUnicodeCodePoints(left.scope, right.scope) || + compareUnicodeCodePoints(left.dimension, right.dimension) || + compareUnicodeCodePoints( + left.source_comparison_id, + right.source_comparison_id, + ); const assertUnique = (values: readonly string[], label: string): void => { if (new Set(values).size !== values.length) diff --git a/src/domain/evidenceBundle.ts b/src/domain/evidenceBundle.ts index 39dcf43e7..dfedeeb70 100644 --- a/src/domain/evidenceBundle.ts +++ b/src/domain/evidenceBundle.ts @@ -1,6 +1,8 @@ import { z } from "zod"; import canonicalize from "canonicalize"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + import { evidenceSchema, immutableEvidence, @@ -72,7 +74,7 @@ export const createEvidenceBundle = ( unknowns: readonly ResidualUnknown[] = [], ): EvidenceBundle => { const sortedRecords = [...records].sort((left, right) => - left.evidence_id.localeCompare(right.evidence_id), + compareUnicodeCodePoints(left.evidence_id, right.evidence_id), ); return { artifacts: uniqueSorted( @@ -117,7 +119,7 @@ export const createEvidenceBundle = ( ), unknowns: [...unknowns].sort( (left, right) => - left.unknown_id.localeCompare(right.unknown_id) || + compareUnicodeCodePoints(left.unknown_id, right.unknown_id) || left.revision - right.revision, ), records: sortedRecords, @@ -517,6 +519,6 @@ const uniqueSorted = (values: readonly Value[]): Value[] => { const unique = new Map(); for (const value of values) unique.set(JSON.stringify(value), value); return [...unique.entries()] - .sort(([left], [right]) => left.localeCompare(right)) + .sort(([left], [right]) => compareUnicodeCodePoints(left, right)) .map(([, value]) => value); }; diff --git a/src/domain/functionComparison.ts b/src/domain/functionComparison.ts index ded6afeab..9eb801694 100644 --- a/src/domain/functionComparison.ts +++ b/src/domain/functionComparison.ts @@ -1,4 +1,5 @@ import { canonicalJson } from "./comparisonSemantics.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { parseFunctionEvidence } from "./functionDossierEvidence.js"; import { functionMatch } from "./functionComparisonNormalization.js"; import { @@ -40,6 +41,6 @@ export const compareFunctions = ( ] : []), ]), - ].sort((a, b) => a.localeCompare(b)), + ].sort((a, b) => compareUnicodeCodePoints(a, b)), }); }; diff --git a/src/domain/functionDossierEvidence.ts b/src/domain/functionDossierEvidence.ts index 852b0faeb..5a1443c1c 100644 --- a/src/domain/functionDossierEvidence.ts +++ b/src/domain/functionDossierEvidence.ts @@ -1,4 +1,5 @@ import { parseEvidence, type Evidence } from "./evidence.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { functionDossierSchema, type FunctionDossier } from "./hopperValues.js"; /** Complete function observation parsed from one analyze_function Evidence record. */ @@ -25,6 +26,6 @@ export const parseFunctionEvidence = (input: unknown): FunctionSnapshot => { dossier, limitations: [ ...new Set([...evidence.limitations, ...dossier.limitations]), - ].sort((left, right) => left.localeCompare(right)), + ].sort((left, right) => compareUnicodeCodePoints(left, right)), }; }; diff --git a/src/domain/javascript/sourceToBundleSignals.ts b/src/domain/javascript/sourceToBundleSignals.ts index 719062200..53dd8a842 100644 --- a/src/domain/javascript/sourceToBundleSignals.ts +++ b/src/domain/javascript/sourceToBundleSignals.ts @@ -326,11 +326,11 @@ const uniquePaths = (paths: readonly CurrentPath[]): CurrentPath[] => path, ]), ).values(), - ].sort((left, right) => - compareUnicodeCodePoints( - `${left.kind}\0${left.value}`, - `${right.kind}\0${right.value}`, - ), + ].sort( + (left, right) => + compareUnicodeCodePoints(left.kind, right.kind) || + compareUnicodeCodePoints(left.value, right.value) || + Number(left.allowSuffix) - Number(right.allowSuffix), ); const pathSuffixes = (path: string): string[] => { diff --git a/src/domain/jsonShape.test.ts b/src/domain/jsonShape.test.ts index b4e4e4a1b..dc37bb6d4 100644 --- a/src/domain/jsonShape.test.ts +++ b/src/domain/jsonShape.test.ts @@ -102,15 +102,11 @@ describe("inferJsonShape", () => { }, ); - it("preserves the existing locale order for paths that do not tie", () => { + it("orders paths deterministically by Unicode code point", () => { const names = ["z", "é", "A", "_", "a"]; - const expected = names - .map((name) => `/${name}`) - .sort((left, right) => left.localeCompare(right)); - expect(new Set(expected).size).toBe(names.length); - for (const [index, left] of expected.entries()) - for (const right of expected.slice(index + 1)) - expect(left.localeCompare(right)).not.toBe(0); + // Code-point order (locale-independent): A < _ < a < z < é. + // `localeCompare` order varies by host ICU and must not leak into evidence. + const expected = ["/A", "/_", "/a", "/z", "/é"]; const shape = inferJsonShape( JSON.stringify(Object.fromEntries(names.map((name) => [name, true]))), ); diff --git a/src/domain/jsonShape.ts b/src/domain/jsonShape.ts index 2defacd58..f8d844aaf 100644 --- a/src/domain/jsonShape.ts +++ b/src/domain/jsonShape.ts @@ -90,11 +90,7 @@ export const inferJsonShape = (text: string): JsonShape | null => { types: [...value.types].sort(), observations: value.observations, })) - .sort( - (left, right) => - left.path.localeCompare(right.path) || - compareUnicodeCodePoints(left.path, right.path), - ), + .sort((left, right) => compareUnicodeCodePoints(left.path, right.path)), }); }; diff --git a/src/domain/native/objcSwiftMetadata.ts b/src/domain/native/objcSwiftMetadata.ts index 807c5dffd..6b4e13cb5 100644 --- a/src/domain/native/objcSwiftMetadata.ts +++ b/src/domain/native/objcSwiftMetadata.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; + /** Objective-C method type. */ export const objcMethodTypeSchema = z.enum([ "instance", @@ -395,9 +397,8 @@ export const inspectNativeDispatchMetadata = ( })); const decodedImplementations = [...implementations.values()].sort( (left, right) => - `${left.class_name}:${left.selector}`.localeCompare( - `${right.class_name}:${right.selector}`, - ), + compareUnicodeCodePoints(left.class_name, right.class_name) || + compareUnicodeCodePoints(left.selector, right.selector), ); const swift = swiftSymbols.length > 0; diff --git a/src/domain/reconstructionCoverage.ts b/src/domain/reconstructionCoverage.ts index 80349b36a..1f7d6a318 100644 --- a/src/domain/reconstructionCoverage.ts +++ b/src/domain/reconstructionCoverage.ts @@ -3,6 +3,8 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + import { evidenceBundleSchema, parseEvidenceBundle } from "./evidenceBundle.js"; import { evaluateReconstructionClaims, @@ -403,9 +405,8 @@ const closureStatus = ( }; const reasonOrder = (left: ClosureReason, right: ClosureReason): number => - `${left.code}:${left.subject_id}`.localeCompare( - `${right.code}:${right.subject_id}`, - ); + compareUnicodeCodePoints(left.code, right.code) || + compareUnicodeCodePoints(left.subject_id, right.subject_id); const digest = (value: unknown): string => { const encoded = canonicalize(value); diff --git a/src/domain/reconstructionUnknowns.ts b/src/domain/reconstructionUnknowns.ts index 8af5593f1..c43330215 100644 --- a/src/domain/reconstructionUnknowns.ts +++ b/src/domain/reconstructionUnknowns.ts @@ -1,4 +1,5 @@ import { uniqueSorted } from "./canonicalOrdering.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import type { ReconstructionClaim, ReconstructionClaimResult, @@ -63,7 +64,7 @@ export const reconstructionClaimUnknowns = ( return unknown === undefined ? [] : [unknown]; }) .sort((left, right) => - left.unknown_id.localeCompare(right.unknown_id, "en"), + compareUnicodeCodePoints(left.unknown_id, right.unknown_id), ); }; @@ -103,11 +104,10 @@ export const reconstructionProbes = ( output.set(key, current); } } - const sorted = [...output.values()].sort((left, right) => - `${left.operation}\0${left.rationale}`.localeCompare( - `${right.operation}\0${right.rationale}`, - "en", - ), + const sorted = [...output.values()].sort( + (left, right) => + compareUnicodeCodePoints(left.operation, right.operation) || + compareUnicodeCodePoints(left.rationale, right.rationale), ); return sorted; }; diff --git a/src/domain/reconstructionVerification.ts b/src/domain/reconstructionVerification.ts index 2b4172bbd..3dd9e3baf 100644 --- a/src/domain/reconstructionVerification.ts +++ b/src/domain/reconstructionVerification.ts @@ -6,6 +6,7 @@ import { z } from "zod"; import { artifactComparisonResultSchema } from "./artifactComparison.js"; import { artifactInventoryResultSchema } from "./artifactGraph.js"; import { uniqueSorted } from "./canonicalOrdering.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { comparisonSourceEvidenceSides } from "./comparisonSourceEvidence.js"; import { parseEvidence, type Evidence } from "./evidence.js"; import { parseEvidenceBundle } from "./evidenceBundle.js"; @@ -76,7 +77,9 @@ export const verifyReconstruction = ( const heads = reconstructionUnknownHeads(bundle.unknowns); const results = specification.claims .map((claim) => evaluateClaim(claim, records, heads)) - .sort((left, right) => left.claim_id.localeCompare(right.claim_id, "en")); + .sort((left, right) => + compareUnicodeCodePoints(left.claim_id, right.claim_id), + ); const failed = count(results, "fail"); const unresolved = count(results, "unknown"); const probes = reconstructionProbes(results, heads); @@ -88,7 +91,7 @@ export const verifyReconstruction = ( specification_sha256: digest({ ...specification, claims: [...specification.claims].sort((left, right) => - left.claim_id.localeCompare(right.claim_id, "en"), + compareUnicodeCodePoints(left.claim_id, right.claim_id), ), }), summary: { diff --git a/src/domain/residualUnknown.ts b/src/domain/residualUnknown.ts index 7695c340c..f85996c29 100644 --- a/src/domain/residualUnknown.ts +++ b/src/domain/residualUnknown.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { prefixedDigestSchema } from "./../domain/digests.js"; const evidenceIdSchema = prefixedDigestSchema("ev"); @@ -287,13 +288,13 @@ const canonicalJson = (value: unknown): string => { }; const sortedUnique = (values: readonly string[]): string[] => - [...new Set(values)].sort((left, right) => left.localeCompare(right)); + [...new Set(values)].sort(compareUnicodeCodePoints); const sortedRelationships = ( values: readonly z.infer[], ): z.infer[] => - [...values].sort((left, right) => - `${left.type}:${left.unknown_id}`.localeCompare( - `${right.type}:${right.unknown_id}`, - ), + [...values].sort( + (left, right) => + compareUnicodeCodePoints(left.type, right.type) || + compareUnicodeCodePoints(left.unknown_id, right.unknown_id), ); diff --git a/src/domain/staticRuntimeCorrelation.ts b/src/domain/staticRuntimeCorrelation.ts index ff7705d57..b00f5a3d5 100644 --- a/src/domain/staticRuntimeCorrelation.ts +++ b/src/domain/staticRuntimeCorrelation.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { artifactComparisonResultSchema } from "./artifactComparison.js"; import { uniqueSorted } from "./canonicalOrdering.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { comparisonSourceEvidenceIds } from "./comparisonSourceEvidence.js"; import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js"; import { functionComparisonResultSchema } from "./functionComparisonSchemas.js"; @@ -175,7 +176,7 @@ export const correlateStaticAndRuntime = ( const correlations = parsed.mappings .map((mapping) => correlate(mapping, staticById, runtimeById)) .sort((left, right) => - left.correlation_id.localeCompare(right.correlation_id, "en"), + compareUnicodeCodePoints(left.correlation_id, right.correlation_id), ); if ( new Set(correlations.map(({ correlation_id: id }) => id)).size !== diff --git a/src/domain/webCaptureDiff.ts b/src/domain/webCaptureDiff.ts index c0ac4698a..cee5096d3 100644 --- a/src/domain/webCaptureDiff.ts +++ b/src/domain/webCaptureDiff.ts @@ -1,4 +1,5 @@ import { digestCanonicalValue } from "./canonicalDigest.js"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import type { WebPageInspection } from "./browserObservationSchemas.js"; import { webCaptureDiffSchema, @@ -59,8 +60,8 @@ const compareIdentities = ( if (!before.has(identity)) changes.push({ identity, change: "added" }); return changes.sort( (left, right) => - left.identity.localeCompare(right.identity) || - left.change.localeCompare(right.change), + compareUnicodeCodePoints(left.identity, right.identity) || + compareUnicodeCodePoints(left.change, right.change), ); }; @@ -301,7 +302,12 @@ const incompleteSections = (completeness: { const domProjection = (inspection: WebPageInspection) => ({ frames: inspection.frames .map(({ url, origin }) => ({ url, origin })) - .sort((left, right) => left.url.localeCompare(right.url)), + .sort( + (left, right) => + compareUnicodeCodePoints(left.url, right.url) || + compareUnicodeCodePoints(left.origin ?? "", right.origin ?? "") || + Number(left.origin !== null) - Number(right.origin !== null), + ), nodes: inspection.dom.nodes.map(({ index: _index, ...node }) => node), }); diff --git a/src/domain/webInventory.ts b/src/domain/webInventory.ts index 11c2d0caa..1ea051951 100644 --- a/src/domain/webInventory.ts +++ b/src/domain/webInventory.ts @@ -2,6 +2,8 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; +import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; + export interface WebInventoryResourceInput { readonly url: string; readonly origin: string | null; @@ -42,8 +44,8 @@ export const stableWebResources = ( ).values(), ].sort( (left, right) => - left.resource_key.localeCompare(right.resource_key) || - left.url.localeCompare(right.url), + compareUnicodeCodePoints(left.resource_key, right.resource_key) || + compareUnicodeCodePoints(left.url, right.url), ); }; diff --git a/tests/boundary/mcp/browserComparisonInput.test.ts b/tests/boundary/mcp/browserComparisonInput.test.ts index b94a14783..66104d292 100644 --- a/tests/boundary/mcp/browserComparisonInput.test.ts +++ b/tests/boundary/mcp/browserComparisonInput.test.ts @@ -59,15 +59,31 @@ describe("browser comparison input boundary", () => { inspectWebPageInputSchema.parse({ cdp_endpoint: browser.endpoint, target_id: "allowed-page", + allowed_origins: [ + browser.allowedOrigin, + "https://private.example.test", + ], observation_ms: 0, include_json_body_shapes: true, include_websocket_shapes: true, }), ); if (!produced.ok) throw produced.error; + // The same frame URL can occur under different origins. Capture order + // must not turn identical frame identities into a DOM change. + produced.value.frames = [null, browser.allowedOrigin, ""].map( + (origin, index) => ({ + frame_id: String(index), + parent_frame_id: null, + url: "about:blank", + origin, + }), + ); + const reordered = structuredClone(produced.value); + reordered.frames.reverse(); const passive = { before: { inspection: produced.value }, - after: { inspection: produced.value }, + after: { inspection: reordered }, }; const scenario = contract.examples[0]?.input; if (scenario === undefined) throw new Error("Missing scenario example"); @@ -131,9 +147,8 @@ describe("browser comparison input boundary", () => { }); } const parsedPassive = browserCaptureComparisonInputSchema.parse(passive); - expect(parsedPassive).toEqual({ - before: { inspection: produced.value, webmcp: null }, - after: { inspection: produced.value, webmcp: null }, + expect(compareBrowserCaptures(parsedPassive)).toMatchObject({ + dimensions: { dom_structure: { status: "unchanged" } }, }); expect(compareBrowserCaptures(parsedPassive).overall_status).toBe( "unknown", From ba4422296dc409d49836f25642555e00463bfe3b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:22:35 +0800 Subject: [PATCH 102/189] docs: consolidate agent guidance around ownership and boundaries --- AGENTS.md | 121 +++++++++++++++----------------------------- docs/tool-design.md | 6 +++ 2 files changed, 46 insertions(+), 81 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index abfd2e301..334d1333c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,116 +1,75 @@ # Repository Guidelines -## Product Direction +## Product and Authority -REA exposes reverse-engineering tools through a CLI and MCP server. Hopper, the bring-your-own Ghidra adapter, and the bring-your-own IDA MCP adapter are operation-capable deep binary-analysis providers. Ghidra is supported on Linux x64/arm64 and macOS x64/arm64 with matching native decompiler tools, and has an experimental Windows x64 P0 boundary for approved native x86 and x86-64 PE applications; on Linux and macOS it supplies inventory, function analysis, and atomic function annotation edits in an ephemeral database, without modifying executable bytes or controlling a GUI. Windows P0 has no mutation authority. IDA adapts upstream legacy attached GUI and modern headless database-supervisor profiles for live read-only analysis; initial real verification covers Windows, and an attached GUI database is never saved or closed. Keep provider-specific code out of the domain and application layers. +REA is a local-only reverse-engineering tool exposed through a CLI and MCP server. Keep observed, derived, inferred, and unknown results distinct. Shared application workflows must provide equivalent CLI/MCP behavior, including Evidence provenance and session retention. Provider support and setup live in [README.md](README.md#choosing-a-deep-analysis-provider) and the linked provider guides. -Prioritize: +Preserve provider authority boundaries: Ghidra uses an ephemeral analysis database without modifying executable bytes or controlling a GUI; Windows Ghidra P0 has no mutation authority. IDA analysis is read-only, and an attached GUI database is never saved or closed. -- tool results that distinguish observations, inferences, and unknowns; -- equivalent behavior through the CLI and MCP; -- additive, idempotent configuration with backups; -- end-to-end tests for packaged artifacts and real Hopper/Ghidra claims. +Configuration changes must be additive and idempotent, with backups. Installers must not install or upgrade Homebrew, Node.js, npm, Java, Ghidra, or other unrelated software. Ghidra and IDA are bring-your-own. `rea setup` must print its planned changes and require approval before writing files or installing Hopper. -Installers must not install or upgrade Homebrew, Node.js, npm, Java, Ghidra, or other unrelated software. Ghidra is bring-your-own. `rea setup` must print its planned changes and require approval before writing files or installing Hopper. +Preserve caller-selected inputs, captured output, URLs, paths, digests, mismatch locations, and analysis metadata. Redact transport authentication credentials and values the caller explicitly marks sensitive; do not infer secrecy from names or text patterns, or persist the entire ambient environment merely because a child inherits it. -REA is a local-only tool. Preserve caller-selected inputs, captured output, URLs, paths, digests, mismatch locations, and analysis metadata. Do not guess that local evidence is secret from environment-variable names, argument names, or text patterns. Redact transport authentication credentials and values the caller explicitly marks sensitive; do not persist the entire ambient environment merely because a child inherits it. +## Architecture and Ownership -## Project Structure & Module Organization - -REA is a layered ESM TypeScript application. Dependencies flow inward from pure domain logic through contracts, providers, application workflows, and CLI/MCP adapters. See [docs/architecture.mermaid](docs/architecture.mermaid) for the component map. +REA is a layered ESM TypeScript application. Dependencies flow inward; see [docs/architecture.mermaid](docs/architecture.mermaid). - `src/domain/` owns pure provider-neutral semantics; `src/contracts/` owns caller-visible schemas and the canonical tool inventory. -- `src/hopper/`, `src/ghidra/`, `src/ida/`, `src/browser/`, `src/inspector/`, `src/native/`, `src/artifacts/`, and `src/dotnet/` own provider-specific boundaries. Keep provider protocols out of domain and application code. -- `src/application/` composes shared CLI/MCP workflows, including Evidence provenance, unknowns, and eligible snapshot bindings; `src/server/` translates MCP requests; `src/cli.ts` and `src/main.ts` are the CLI and MCP entry points. -- `src/process/` owns shared process lifecycle primitives, not provider wire protocols. Reuse its supervision and identity primitives before adding provider-local lifecycle code; a PID and executable pathname alone do not establish ownership after exit or reuse. `bridge/` contains provider-side adapters. -- `tests/` contains unit, composition, boundary, acceptance, and conformance tests. `scripts/verify-*` and capability directories under `scripts/verify/` contain real-toolchain checks. -- `docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored build outputs. Update source contracts and authored instructions in `skill-src/`, then run `npm run docs:generate`; never commit derived catalog digests or portable conformance projections. -- `.cache/mcp-tool-catalog.json` is generated test metadata. Generate it with `npm run mcp-catalog:generate`; source checking and runtime builds do not consume it. +- Provider directories own engine protocols and parsing. Keep provider-specific code out of domain and application layers; `bridge/` contains provider-side adapters. +- `src/application/` owns shared workflows and Evidence/session semantics. `src/server/` translates MCP requests; `src/cli.ts` and `src/main.ts` are the CLI and MCP entry points. +- `src/process/` owns shared lifecycle primitives. Reuse its supervision and identity checks; a PID and executable pathname alone do not establish ownership after exit or reuse. +- `src/config/` owns configuration parsing. Keep user-facing setup and environment documentation in [README.md](README.md) and the relevant provider guide. -## Build, Test, and Development Commands +Assess brittleness during implementation, debugging, review, and maintenance. Give each interpretation and resource a clear owner. Preserve identity, omission, uncertainty, and source evidence across boundaries. Retain ownership of resources whose cleanup failed. Fix the producing representation or ownership rule before adding downstream repairs. -- `npm ci`: install the locked dependencies. -- `npm run build:cached`: compile the CLI/MCP runtime and bundle its authored skill. Test catalogs and documentation/conformance artifacts have separate tasks. -- `npm run test:local`: run changed source tests without building; pass exact source test paths to run them regardless of Git status. -- `npm run test:focused -- PATH...`: run exact test files, preparing runtime and generated artifacts required by the selected tests. -- `npm run check:changed`: run cached static checks and source tests affected since the branch merge base (default `origin/main`). -- `npm run check:fast`: run cached typecheck and lint checks. -- `npm run check:pr`: opt into the complete local deterministic gate and generated-document checks for broad changes; CI owns full coverage. Routine iterations need focused tests and relevant checks, not the whole gate each time. -- `npm run docs:check`: build and validate generated documents for the current checkout; `npm run docs:generate` regenerates them. CI retains ignored outputs as artifacts and does not push snapshot commits to feature branches. -- For provider-dependent changes, see [docs/testing.md](docs/testing.md) and run the matching real-provider verification. -- Keep each verification lane's prerequisites limited to the claim it checks. Use host-native fixtures for host/provider acceptance; put optional cross-target formats and their external toolchains in a separate lane. Preflight required commands and report the missing dependency and lane clearly. +Simplify duplicated rules, scattered defaults, caller-specific exceptions, and unclear invariants in touched code. Prefer standard format-aware parsers and existing shared helpers; normalize once at the owning boundary. Remove superseded representations, aliases, wrappers, and tests when their replacement is verified through affected consumers. Keep refactors focused on the task and introduce abstractions only when they remove observed complexity. -See [docs/testing.md](docs/testing.md) for test scopes and verification lanes and [CONTRIBUTING.md](CONTRIBUTING.md) for contribution checks. Pre-commit formats and lints staged source; pre-push runs `npm run check:fast`. +## Development and Generated Files -## Configuration & Environment Variables +Use the Node.js version in [.nvmrc](.nvmrc) and npm version in `package.json#packageManager`. Confirm the active toolchain before installing dependencies. In Cursor Cloud, the image may put an older Node.js first on `PATH`; prepend `/usr/local/bin`, where environment setup installs the pinned toolchain. -Configuration is parsed and validated by `src/config/`. Keep user-facing setup and provider configuration in [README.md](README.md) and the relevant guide under `docs/`; do not maintain a second environment-variable catalogue here. +- `npm ci`: install locked dependencies. +- `npm run build:cached`: compile the runtime and bundle its authored skill; test catalogs and documentation artifacts have separate tasks. +- `npm run test:local -- PATH...`: run source tests without building; explicit paths run regardless of Git status. +- `npm run test:focused -- PATH...`: run exact test files with their required runtime and generated artifacts. +- `npm run check:changed`: run static checks and source tests affected since the merge base, defaulting to `origin/main`. +- `npm run check:fast`: run cached typecheck and lint checks; also runs before push. +- `npm run check:pr`: complete local deterministic gate and generated-document checks for broad changes. Routine iterations need focused tests and relevant checks; CI owns full coverage. +- `npm run docs:generate` / `npm run docs:check`: generate / validate documentation artifacts. -## Coding Style & Naming Conventions +`docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored build outputs. Edit source contracts and authored instructions in `skill-src/`; never commit derived catalog digests or portable conformance projections. `.cache/mcp-tool-catalog.json` is test metadata generated by `npm run mcp-catalog:generate`; source checking and runtime builds do not consume it. CI retains generated outputs as artifacts rather than pushing them to feature branches. -Use ESM TypeScript, two-space indentation, and the committed Oxfmt configuration. Keep compiler strictness intact (`strict`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, `verbatimModuleSyntax`). Use `camelCase` for values/functions, `PascalCase` for classes/types, and `UPPER_SNAKE_CASE` for constants. Parse unknown values at every MCP, environment, and subprocess boundary. Avoid `any`, unchecked casts, non-null assertions, import-time I/O, and floating promises. Exported APIs require concise JSDoc. Model expected failures with the tagged error algebra and `Result`, not broad exception wrappers. +See [docs/testing.md](docs/testing.md) for verification lanes and [CONTRIBUTING.md](CONTRIBUTING.md) for contribution checks. Keep each lane's prerequisites limited to its claim; separate host-native acceptance from optional cross-target toolchains and preflight required commands. JavaScript analysis and deterministic tests do not require Hopper, Ghidra, or IDA. -Assess brittleness during implementation, debugging, review, and maintenance. Simplify duplicated rules, scattered defaults, caller-specific exceptions, and unclear invariants in touched code. Prefer standard format-aware parsers and existing shared helpers; normalize once at the owning boundary while preserving source evidence. Keep refactors focused on the task, and introduce abstractions only when they remove observed complexity. Verify preserved behavior and corrected edge cases through affected callers. +## Coding and Boundary Contracts -## Boundary Contracts +Use ESM TypeScript, two-space indentation, and committed Oxfmt formatting. Preserve compiler strictness, including `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, and `verbatimModuleSyntax`. Use `camelCase` for values/functions, `PascalCase` for classes/types, and `UPPER_SNAKE_CASE` for constants. Exported APIs require concise JSDoc. Avoid `any`, unchecked casts, non-null assertions, import-time I/O, and floating promises. Model expected failures with the tagged error algebra and `Result`. -Treat a boundary as a contract between the producer's actual representation and the consumer's required meaning. When implementing or auditing a boundary, trace the value through parsing, normalization, authorization, serialization, and the CLI/MCP result. Establish affected callers from their code paths; similar tool names or workflows do not prove that they share a schema or failure mode. +Parse unknown values at MCP, environment, and subprocess boundaries. Trace the producer's actual representation through parsing, normalization, authorization, serialization, and the consumer result. Establish affected callers from code paths; inspect adjacent representations and failure paths when changing a boundary. -When changing boundary behavior, inspect adjacent input representations, failure paths, and affected callers, and correct the underlying assumption across those cases. +Keep identity, provenance, matching, and path-resolution values separate from display formatting. Absolute filesystem paths, file URLs, and HTTP paths have different semantics. Interpret provider metadata according to its producer; preserve source values and explicit unknowns when normalization loses information. Display placeholders must not feed lookup or selection. -Keep portable evidence and scenario validation distinct from host-native execution checks. Absolute filesystem paths, file URLs, and HTTP paths have different semantics; do not substitute one platform's syntax for the domain concept. Interpret provider metadata according to its documented or observed producer behavior. Keep values used for identity, provenance, matching, and path resolution separate from display formatting. When normalization loses information, preserve the source value and an explicit unknown; display placeholders must not feed back into lookup or selection. +Preserve partial facts without inventing missing metadata or requiring another provider's full representation. Inspect installed APIs and representative producer objects before claiming a capability is unavailable. Preserve meaningful failure reasons and actionable recovery guidance: malformed input, unsupported targets, unavailable providers, and host permission denial are distinct. Collected observations must survive execution and cleanup failures. -Preserve meaningful failure reasons through application and adapter layers. Malformed input is distinct from an unsupported target, unavailable provider, or host operating-system permission denial. Diagnostics should identify the failed constraint and the target or lifecycle request it applies to. Recovery advice must address that reason and point to an available workflow; generic catches must not erase actionable validation details. Preserve collected observations on execution failure independently of whether cleanup succeeds. +Validate advertised input and output JSON Schemas against their declared dialect after SDK conversion, and verify client compatibility at the consuming boundary. Bind handlers to named contracts with exact input/output types; catalog ordering must never select an operation or schema. -Preserve partial native facts. A shared schema must not require one provider's full metadata before another provider can report the facts it observes. Keep observed classifications and endpoints alongside explicit unknowns for unsupported flags; never invent missing flags or discard known facts to satisfy an all-or-nothing availability shape. Before claiming a native API lacks a capability, inspect the installed API and probe representative producer objects. Exercise the resulting partial representation through CLI, MCP, and composed results such as function dossiers. +## Tool Design and Verification -Leave meaningful target, action, capture, and output choices to the agent. A selected operation already expresses intent; do not require approval booleans or repeated permission declarations. Trace each setting to its consumer: remove ignored options and single-value confirmations, derive built-in lifecycle behavior, and supply defaults for omitted optional metadata. Report actual effects and limitations where they help interpret results rather than asking callers to restate them. +Start from the analyst question and inspect existing contracts before adding a tool. Prefer reusable primitives and ordinary commands/scripts for experiments; add composed workflows for observed recurring needs. Leave meaningful target, action, capture, and output choices to the caller. Remove ignored settings and repeated approval declarations; derive built-in lifecycle behavior and default optional metadata. -Verify the representation consumed at the next boundary. Internal validator success does not establish JSON Schema validity or client compatibility: validate advertised input and output schemas against their declared dialect after SDK conversion, and keep generated contracts aligned. Use representative producer data and regressions that exercise the failed behavior. Platform and provider support claims require the corresponding real workflow; package startup, capability probes, and mock transport tests establish only their narrower claims. Report unverified coverage explicitly. +Return useful evidence inline, complete by default, with identity, source locations, relevant limitations, and truthful authority/lifecycle effects. Limits must follow real format, protocol, authority, or resource constraints; account for representation expansion and products of bounded dimensions before allocation. Derive completeness from what was examined and exhausted. Follow [docs/tool-design.md](docs/tool-design.md) for naming, composition, contract design, and representative CLI/MCP usability evaluation. Update canonical contracts and generated artifacts together. -Bind tool handlers to named contracts, preserving their exact input and output types. Catalog ordering is presentation metadata; changing that order must not select a different schema or operation for an existing handler. +Prefer full public CLI/MCP end-to-end workflows with real providers, then production-boundary integration tests, then goldens from real producers. Keep focused module tests for distinct failures or semantics that stronger workflows cannot reliably reproduce. Delete redundant assertions when stronger coverage proves the same claim; preserve distinct malformed-input, cancellation, cleanup, permission, capacity, and target-identity cases. Follow [docs/testing.md](docs/testing.md) for pruning criteria, test classification, fixtures, and verification commands. -## Designing MCP Tools +Use Vitest, `*.test.ts`, production seams rather than module mocks, and the pinned MCP client SDK. Treat advertised examples as executable contracts using representative producer data. Provider/platform and packaged-artifact claims require their real workflows; capability probes and simulated transports prove only their narrower scope. Report unverified coverage explicitly. -Start from the analyst question and desired result, not a provider API. Before adding a tool, inspect the existing contract and its nearest alternative. +Keep tool catalogs complete and self-describing; prefer capability/session-scoped availability over schema truncation. Serialized bytes alone do not establish agent usability or model context cost. -Let agents compose experiments with ordinary commands, scripts, and local fixture servers. REA tools should perform the requested inspection or capture and return evidence. A custom orchestration language, replay engine, or separate prepare/execute plan needs an observed requirement that those primitives cannot satisfy. A plan-only tool without an executor does not establish runtime behavior; expose the useful inspection directly. +## Commits and Pull Requests -- Prefer reusable, composable primitives: inspect one explicit object or - relationship and return evidence that can support different analyst - questions. Compose primitives into a workflow only for a recurring outcome - that benefits from joining evidence sources; keep one-application or - business-domain interpretations out of general tool contracts. -- Use **inspect/search** tools for facts about a target or candidate set; use **trace** tools for relationships; use **compare** tools for explicitly paired inputs. -- Add a **workflow** when observed agent use shows a repeated sequence that REA can compose without losing analyst control. Return useful results inline so callers can choose their next action. -- Use **observe/capture** only when runtime activity is required, and declare authority and lifecycle effects in the contract. -- Extend an existing tool when intent and result contract are unchanged. Add a tool for a distinct analyst outcome or materially different authority. -- Keep caller-facing names and results provider-neutral. Put engine-specific behavior in provider adapters and report each provider's exact coverage. -- Keep results complete by default. Add a limit only when it follows from a real format, protocol, authority, or resource-safety constraint; explain truncation and unsupported facets. Account for representation expansion and products of independently bounded dimensions before allocating or retaining output. Derive facet completeness from what was examined and exhausted, not an empty failure list. Keep observed, derived, inferred, and unknown results distinct. -- Include artifact identity, source locations, Evidence references, actionable errors, and relevant limitations when they affect conclusions. Return the evidence needed for the next analysis inline rather than requiring a resource or identifier lookup. -- Implement shared application workflows behind CLI and MCP adapters. Update canonical contracts and generated catalog together. +Use Conventional Commit subjects, including PR titles for squash merges. Release Please always bumps minor; mark breaking changes with `!` or a `BREAKING CHANGE:` footer. Describe behavior/contract changes, relevant validation, linked issues, and real-provider verification scope; include sanitized CLI/MCP examples for schema changes. -See [docs/tool-design.md](docs/tool-design.md) for the design checklist. When usability or tool selection changes, evaluate representative CLI/MCP tasks as well as schema and transport behavior. - -## Testing Guidelines - -Prefer full end-to-end workflows through the public CLI or MCP with real providers and no mocked dependencies, then integration across production boundaries, then goldens captured from real producers. Keep a focused module test only for a distinct failure or semantic case that stronger workflows cannot reliably reproduce. Delete redundant getter, serialization, enum, count, and snapshot assertions when a stronger consumer workflow already proves the claim. Test paths, compiled imports, and suites named E2E do not establish end-to-end coverage. See [docs/testing.md](docs/testing.md) for pruning and classification rules. - -Treat advertised examples as executable contracts: derive them from representative producer data, exercise them through the advertised CLI or MCP workflow, and assert the behavior they claim to demonstrate. Share production projections where practical and declare omitted coverage explicitly. - -Name tests `*.test.ts`. Use Vitest and production seams (`tests/fixtures/`) rather than module mocks. Domain tests assert pure behavior; adapter tests use fake launcher/socket seams; MCP tests connect with the client SDK version pinned in `package.json`. Preserve the canonical tool inventory defined by `TOOL_CONTRACTS` and verified through `CATALOG_IDENTITY` and generated product metadata. Cover malformed input, cancellation, lifecycle cleanup, and actual format, protocol, host-permission, and target-identity boundaries. Do not add tests that merely freeze arbitrary caps or prescribed call sequences. Real Hopper, Ghidra, browser, managed conformance, and any real managed-tool claims cannot be replaced by mocks; use the corresponding `verify:*` command. - -Keep tool catalogs complete and self-describing; prefer capability- and session-scoped availability over schema truncation. Serialized bytes alone do not measure agent usability or model context cost. - -## Cursor Cloud specific instructions - -Development requires Node.js 24.18.0 and npm 11.16.0 (`.nvmrc` and `packageManager`). The Cloud Agent image places an older `node` on `PATH` ahead of a normal install. Environment setup installs the pinned toolchain under `/usr/local` and prepends `/usr/local/bin` for login shells. Confirm `node -v` is `v24.18.0` before installing dependencies. - -`npm ci` installs locked dependencies. `npm run build:cached` produces the CLI and MCP server. `npm run check:fast` is the pre-push typecheck and lint. Hopper, Ghidra, and IDA are optional bring-your-own providers. JavaScript analysis and the deterministic Vitest suites do not need them. `rea doctor` reports those engines as missing until they are configured. - -## Commit & Pull Request Guidelines - -Use Conventional Commit subjects because Release Please derives changelogs from them. Release Please uses `always-bump-minor`: every release increments minor, including breaking changes. Examples: `feat: add historical source import`, `fix(process): stop timers after exit`, and `docs: update architecture`. Use `!` or a `BREAKING CHANGE:` footer for breaking changes. Pull request titles must follow the same format because squash merges use the title as the release commit. Pull requests should describe contract or behavior changes, list verification commands, link issues, and include sanitized MCP examples when schemas change. State whether real Hopper/Ghidra verification was performed. Never commit binaries, Hopper or Ghidra project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts (e.g. `.codex/`). +Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts such as `.codex/`. Pre-commit formats and lints staged source. diff --git a/docs/tool-design.md b/docs/tool-design.md index 4a5c2fab6..ed8c09aaf 100644 --- a/docs/tool-design.md +++ b/docs/tool-design.md @@ -22,6 +22,12 @@ object agents reason about; keep the name distinct from nearby alternatives. ## Prefer primitives; compose workflows +Let agents compose experiments with ordinary commands, scripts, and local +fixture servers. A custom orchestration language, replay engine, or separate +prepare/execute plan needs an observed requirement those primitives cannot +satisfy. Expose useful inspection directly; a plan-only tool without an executor +does not establish runtime behavior. + Start with a primitive when one call can report a reusable fact about one identified object or relationship, such as an instruction decode, a type layout, a reference, a dispatch target, or a resource graph. The same primitive From 5d79387505ebae1ec8d800ee3ffd901920a9d8be Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:28:13 +0800 Subject: [PATCH 103/189] docs: prune repeated contributor and tool design instructions --- AGENTS.md | 74 ++++++---------- CONTRIBUTING.md | 176 ++++++++++++++------------------------ docs/testing.md | 201 ++++++++++---------------------------------- docs/tool-design.md | 175 +++++++++++++++++--------------------- 4 files changed, 209 insertions(+), 417 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 334d1333c..15d3984ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,74 +2,48 @@ ## Product and Authority -REA is a local-only reverse-engineering tool exposed through a CLI and MCP server. Keep observed, derived, inferred, and unknown results distinct. Shared application workflows must provide equivalent CLI/MCP behavior, including Evidence provenance and session retention. Provider support and setup live in [README.md](README.md#choosing-a-deep-analysis-provider) and the linked provider guides. +REA is a local-only reverse-engineering tool with shared CLI/MCP workflows. Distinguish observations, derivations, inferences, and unknowns; preserve Evidence provenance and session semantics through both adapters. Provider support and setup live in [README.md](README.md#choosing-a-deep-analysis-provider) and its linked guides. -Preserve provider authority boundaries: Ghidra uses an ephemeral analysis database without modifying executable bytes or controlling a GUI; Windows Ghidra P0 has no mutation authority. IDA analysis is read-only, and an attached GUI database is never saved or closed. +Ghidra uses ephemeral databases without modifying executable bytes or controlling a GUI; Windows Ghidra P0 has no mutation authority. IDA analysis is read-only; never save or close an attached GUI database. -Configuration changes must be additive and idempotent, with backups. Installers must not install or upgrade Homebrew, Node.js, npm, Java, Ghidra, or other unrelated software. Ghidra and IDA are bring-your-own. `rea setup` must print its planned changes and require approval before writing files or installing Hopper. +Configuration changes must be additive and idempotent, with backups. Installers must not install or upgrade unrelated software, including Homebrew, Node.js, npm, Java, or Ghidra. Ghidra and IDA are bring-your-own. `rea setup` must show its planned changes and require approval before writing files or installing Hopper. -Preserve caller-selected inputs, captured output, URLs, paths, digests, mismatch locations, and analysis metadata. Redact transport authentication credentials and values the caller explicitly marks sensitive; do not infer secrecy from names or text patterns, or persist the entire ambient environment merely because a child inherits it. +Preserve caller-selected inputs and local evidence, including output, URLs, paths, digests, and metadata. Redact transport authentication credentials and explicitly marked sensitive values; do not infer secrecy from names or text patterns. Do not persist the ambient environment merely because a child inherits it. -## Architecture and Ownership +## Architecture and Cleanup -REA is a layered ESM TypeScript application. Dependencies flow inward; see [docs/architecture.mermaid](docs/architecture.mermaid). +Dependencies flow inward: domain semantics and contracts, provider adapters, shared application workflows, then CLI/MCP adapters. Keep engine protocols and provider-specific code out of domain/application layers. See [docs/architecture.mermaid](docs/architecture.mermaid) when changing composition. -- `src/domain/` owns pure provider-neutral semantics; `src/contracts/` owns caller-visible schemas and the canonical tool inventory. -- Provider directories own engine protocols and parsing. Keep provider-specific code out of domain and application layers; `bridge/` contains provider-side adapters. -- `src/application/` owns shared workflows and Evidence/session semantics. `src/server/` translates MCP requests; `src/cli.ts` and `src/main.ts` are the CLI and MCP entry points. -- `src/process/` owns shared lifecycle primitives. Reuse its supervision and identity checks; a PID and executable pathname alone do not establish ownership after exit or reuse. -- `src/config/` owns configuration parsing. Keep user-facing setup and environment documentation in [README.md](README.md) and the relevant provider guide. +Give each interpretation and resource a clear owner. Preserve identity, omission, uncertainty, and source evidence across boundaries. Retain ownership of resources whose cleanup failed. Reuse `src/process/` supervision and identity primitives; a PID and executable path alone do not establish ownership after exit or reuse. -Assess brittleness during implementation, debugging, review, and maintenance. Give each interpretation and resource a clear owner. Preserve identity, omission, uncertainty, and source evidence across boundaries. Retain ownership of resources whose cleanup failed. Fix the producing representation or ownership rule before adding downstream repairs. +Assess brittleness in touched code during implementation, debugging, review, and maintenance. Fix the producing representation or ownership rule before adding downstream repairs. Normalize once at the owning boundary using format-aware parsers. Remove superseded representations, aliases, wrappers, and redundant tests after verifying affected consumers. Introduce abstractions only when they remove observed complexity. -Simplify duplicated rules, scattered defaults, caller-specific exceptions, and unclear invariants in touched code. Prefer standard format-aware parsers and existing shared helpers; normalize once at the owning boundary. Remove superseded representations, aliases, wrappers, and tests when their replacement is verified through affected consumers. Keep refactors focused on the task and introduce abstractions only when they remove observed complexity. +Parse unknown boundary values and model expected failures with the tagged error algebra and `Result`. Preserve partial facts and meaningful failure reasons. Keep identity and lookup values separate from display formatting; preserve source values and explicit unknowns when normalization loses information. Absolute paths, file URLs, and HTTP paths have different semantics. -## Development and Generated Files +Validate advertised JSON Schemas after SDK conversion against their declared dialect and actual clients. Bind handlers to named contracts with exact types; catalog ordering must never select an operation or schema. -Use the Node.js version in [.nvmrc](.nvmrc) and npm version in `package.json#packageManager`. Confirm the active toolchain before installing dependencies. In Cursor Cloud, the image may put an older Node.js first on `PATH`; prepend `/usr/local/bin`, where environment setup installs the pinned toolchain. +## Development + +Use [.nvmrc](.nvmrc) and `package.json#packageManager` for the pinned toolchain. Cursor Cloud may place older Node.js first on `PATH`; environment setup installs the pinned toolchain under `/usr/local/bin`. - `npm ci`: install locked dependencies. -- `npm run build:cached`: compile the runtime and bundle its authored skill; test catalogs and documentation artifacts have separate tasks. -- `npm run test:local -- PATH...`: run source tests without building; explicit paths run regardless of Git status. -- `npm run test:focused -- PATH...`: run exact test files with their required runtime and generated artifacts. -- `npm run check:changed`: run static checks and source tests affected since the merge base, defaulting to `origin/main`. -- `npm run check:fast`: run cached typecheck and lint checks; also runs before push. -- `npm run check:pr`: complete local deterministic gate and generated-document checks for broad changes. Routine iterations need focused tests and relevant checks; CI owns full coverage. -- `npm run docs:generate` / `npm run docs:check`: generate / validate documentation artifacts. +- `npm run build:cached`: build the runtime and packaged skill. +- `npm run test:local -- PATH...`: source tests without building. +- `npm run test:focused -- PATH...`: exact tests with their required artifacts. +- `npm run check:fast`: cached typecheck/lint and the pre-push check. +- `npm run docs:check`: validate generated documentation. -`docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored build outputs. Edit source contracts and authored instructions in `skill-src/`; never commit derived catalog digests or portable conformance projections. `.cache/mcp-tool-catalog.json` is test metadata generated by `npm run mcp-catalog:generate`; source checking and runtime builds do not consume it. CI retains generated outputs as artifacts rather than pushing them to feature branches. +Use relevant checks for the change. The complete local gate, `npm run check:pr`, is optional for broad changes or CI diagnosis. See [CONTRIBUTING.md](CONTRIBUTING.md) for development, generated-file ownership, and release conventions. -See [docs/testing.md](docs/testing.md) for verification lanes and [CONTRIBUTING.md](CONTRIBUTING.md) for contribution checks. Keep each lane's prerequisites limited to its claim; separate host-native acceptance from optional cross-target toolchains and preflight required commands. JavaScript analysis and deterministic tests do not require Hopper, Ghidra, or IDA. +`docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored outputs. Edit source contracts and `skill-src/`, then regenerate as needed. `.cache/mcp-tool-catalog.json` is test metadata; runtime builds and source checking do not consume it. Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts. -## Coding and Boundary Contracts +## Tool and Test Changes -Use ESM TypeScript, two-space indentation, and committed Oxfmt formatting. Preserve compiler strictness, including `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, and `verbatimModuleSyntax`. Use `camelCase` for values/functions, `PascalCase` for classes/types, and `UPPER_SNAKE_CASE` for constants. Exported APIs require concise JSDoc. Avoid `any`, unchecked casts, non-null assertions, import-time I/O, and floating promises. Model expected failures with the tagged error algebra and `Result`. +For tool design, follow [docs/tool-design.md](docs/tool-design.md): start from the analyst question, reuse existing contracts, preserve caller choices, and return useful evidence inline. Limits must follow real format, protocol, authority, or resource constraints. Account for representation expansion before allocation; derive completeness from examined coverage. -Parse unknown values at MCP, environment, and subprocess boundaries. Trace the producer's actual representation through parsing, normalization, authorization, serialization, and the consumer result. Establish affected callers from code paths; inspect adjacent representations and failure paths when changing a boundary. +For test changes or provider claims, use [docs/testing.md](docs/testing.md). Prefer real public CLI/MCP workflows, then production-boundary integration, then producer goldens. Keep module tests for distinct semantics stronger workflows cannot reliably reproduce. Preserve malformed-input, cancellation, cleanup, permission, capacity, and target-identity coverage when pruning. Report unverified coverage explicitly; simulated providers do not establish real-provider behavior. -Keep identity, provenance, matching, and path-resolution values separate from display formatting. Absolute filesystem paths, file URLs, and HTTP paths have different semantics. Interpret provider metadata according to its producer; preserve source values and explicit unknowns when normalization loses information. Display placeholders must not feed lookup or selection. - -Preserve partial facts without inventing missing metadata or requiring another provider's full representation. Inspect installed APIs and representative producer objects before claiming a capability is unavailable. Preserve meaningful failure reasons and actionable recovery guidance: malformed input, unsupported targets, unavailable providers, and host permission denial are distinct. Collected observations must survive execution and cleanup failures. - -Validate advertised input and output JSON Schemas against their declared dialect after SDK conversion, and verify client compatibility at the consuming boundary. Bind handlers to named contracts with exact input/output types; catalog ordering must never select an operation or schema. - -## Tool Design and Verification - -Start from the analyst question and inspect existing contracts before adding a tool. Prefer reusable primitives and ordinary commands/scripts for experiments; add composed workflows for observed recurring needs. Leave meaningful target, action, capture, and output choices to the caller. Remove ignored settings and repeated approval declarations; derive built-in lifecycle behavior and default optional metadata. - -Return useful evidence inline, complete by default, with identity, source locations, relevant limitations, and truthful authority/lifecycle effects. Limits must follow real format, protocol, authority, or resource constraints; account for representation expansion and products of bounded dimensions before allocation. Derive completeness from what was examined and exhausted. Follow [docs/tool-design.md](docs/tool-design.md) for naming, composition, contract design, and representative CLI/MCP usability evaluation. Update canonical contracts and generated artifacts together. - -Prefer full public CLI/MCP end-to-end workflows with real providers, then production-boundary integration tests, then goldens from real producers. Keep focused module tests for distinct failures or semantics that stronger workflows cannot reliably reproduce. Delete redundant assertions when stronger coverage proves the same claim; preserve distinct malformed-input, cancellation, cleanup, permission, capacity, and target-identity cases. Follow [docs/testing.md](docs/testing.md) for pruning criteria, test classification, fixtures, and verification commands. - -Use Vitest, `*.test.ts`, production seams rather than module mocks, and the pinned MCP client SDK. Treat advertised examples as executable contracts using representative producer data. Provider/platform and packaged-artifact claims require their real workflows; capability probes and simulated transports prove only their narrower scope. Report unverified coverage explicitly. - -Keep tool catalogs complete and self-describing; prefer capability/session-scoped availability over schema truncation. Serialized bytes alone do not establish agent usability or model context cost. - -## Commits and Pull Requests - -Use Conventional Commit subjects, including PR titles for squash merges. Release Please always bumps minor; mark breaking changes with `!` or a `BREAKING CHANGE:` footer. Describe behavior/contract changes, relevant validation, linked issues, and real-provider verification scope; include sanitized CLI/MCP examples for schema changes. - -Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts such as `.codex/`. Pre-commit formats and lints staged source. +Use Conventional Commit subjects and PR titles. Mark breaking changes with `!` or a `BREAKING CHANGE:` footer. Describe behavior changes, relevant validation, and real-provider verification scope. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cce65e730..c60c1e9e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,29 +1,14 @@ # Contributing to REA -REA welcomes focused bug fixes, documentation improvements, tests, and reverse-engineering workflow enhancements. Open an issue before a large contract or architecture change so its scope can be agreed before implementation. +REA welcomes focused bug fixes, documentation improvements, tests, and reverse-engineering workflows. For large contract or architecture changes, explain the intended scope and link the relevant issue or design discussion. ## Choosing a contribution -Small contributions are welcome when they solve a concrete problem, including -broken commands, misleading documentation, and missing regression coverage. -Explain the problem, keep the diff focused, and share how you checked the change. - -Please avoid standalone cosmetic changes without a clear benefit, such as fixing -a typo in an internal comment, changing capitalization or punctuation in -already-clear prose, or reformatting unchanged code. Include related polish in a -useful fix when practical. For cosmetic-only suggestions, please open an issue -instead of a standalone PR so they can be collected and addressed together. -Corrections to confusing explanations or incorrect instructions are welcome. - -Avoid speculative cleanup without a concrete problem to solve. Keep related -corrections in one PR. - -Before requesting review, read the final diff and run the relevant checks. Be clear -about anything you couldn't test. You should be able to explain the changes you -submit. - -We may decline changes when the benefit doesn't justify the review or maintenance -work. +Explain the concrete problem, keep related corrections together, and report +verification and unavailable coverage. Contributions should justify their review +and maintenance cost. Keep cosmetic polish with useful fixes; confusing or +incorrect user instructions warrant standalone corrections. Collect other +cosmetic-only suggestions in an issue rather than separate PRs. For capability organization and provider composition, follow the incremental [migration guide](docs/capability-migration.md). Run `npm run verify:test-discovery` @@ -33,7 +18,10 @@ When adding or changing an MCP tool, follow the [tool design guide](docs/tool-de ## Development setup -REA development requires Node.js 24.18.x and npm 11.16.x (pinned toolchain via `nvm use`; the supported runtime range is Node.js ^22.19 || ^24.11 || >=26, as the README badge states). Real-Hopper verification additionally requires either macOS 12+ or an officially supported Linux host (Ubuntu 24.04+, Fedora 41+, 64-bit Arch, or CachyOS) and an installed Hopper application. Linux demo verification uses its own private Xvfb display and does not require a desktop session. Run `nvm use` before installing dependencies. +Use the development toolchain pinned in `.nvmrc` and +`package.json#packageManager`. Run `nvm use` before installing dependencies; +installed-package runtime support is documented in +[installation](docs/installation.md#start-setup). ```bash npm ci @@ -48,7 +36,8 @@ catalogs, documentation projections, or managed verification evidence. Turbo caches deterministic builds and static checks across Git worktrees. After a package, lockfile, or managed-skill version change, run `npm run metadata:generate` before building. -Keep dependencies flowing inward through the existing domain, contracts, provider, application, server, and adapter layers. Parse unknown values at process and protocol boundaries, model expected failures with `Result`, and preserve the canonical tool inventory defined by `TOOL_CONTRACTS` unless a deliberate contract change updates every verifier, generated catalog artifact, and snapshot. Keep tool discovery complete and report capability- and session-scoped availability through `binary_session`. +Repository invariants live in [AGENTS.md](AGENTS.md). Keep provider-specific +protocols in adapters and shared CLI/MCP workflows in the application layer. ## Documentation website @@ -74,112 +63,77 @@ The separate GitHub Pages host uses only the manual ## Development feedback and PR verification -For an ordinary edit, run the relevant regression and cached static checks: +Select checks for the behavior changed. For a source edit: ```bash npm run test:focused -- src/config.test.ts npm run check:fast ``` -`test:local` selects dirty source tests without building; explicit source test -paths run even on a clean tree. `check:changed` adds source tests affected since -the branch merge base with `origin/main`. Use `npm run test:changed -- --base -REVISION` to choose another base. Changed-test selection follows the import -graph and is feedback, not complete correctness evidence. Inspect relevant -boundary and provider behavior explicitly; see [docs/testing.md](docs/testing.md). +`test:local` runs source tests without building. `check:changed` combines cached +static checks with source tests affected since the merge base with `origin/main`. +Import-graph selection can miss runtime registration, bridges, and generated data; +select relevant boundary tests explicitly. See [testing](docs/testing.md#developer-commands) +for commands, test placement, pruning, and real-provider prerequisites. -Before handing off a PR, run the relevant tests, `npm run check`, and -`npm run docs:check` when contracts or generated metadata change. Record which -checks ran. CI owns complete deterministic tests and aggregate coverage. Use -`npm run check:pr` for a deliberate full local gate on broad changes or when -investigating CI failures; it is not required after each edit, rebase, or push. -Packaging, setup, installation, or distribution changes also require -`npm run verify:package` and `npm pack --dry-run`. Provider behavior changes -require the matching real-provider `verify:*` lane. +Before requesting review, run relevant tests and `npm run check`; add +`npm run docs:check` when contracts or generated metadata change. Record the +checks and unavailable coverage. CI owns the full deterministic suite and +coverage. `npm run check:pr` is an optional full local gate for broad changes or +CI diagnosis. Packaging/setup/distribution changes additionally require +`npm run verify:package` and `npm pack --dry-run`; provider changes require the +matching real-provider lane. State which host/provider workflows ran. -`check:fast` runs cached source/test typecheck and lint without compiling or -running generators. `npm run test:prepare` prepares all artifacts consumed by -the complete suite; focused tests prepare only their runtime and declared -artifact dependencies. The test-only MCP catalog lives at -`.cache/mcp-tool-catalog.json` and can be regenerated independently with -`npm run mcp-catalog:generate`. +Pre-commit formats and lints staged files; pre-push runs `check:fast`. -Build and generation commands hold one SQLite exclusive transaction around -their whole Turbo graph, including cache restoration. The persistent database -in `.cache/rea-command-locks/` is a lock identity, not a stale-file marker; -the operating system releases ownership when the command supervisor exits. -On POSIX, that supervisor retains the transaction and process-group identity -through cancellation, including loss of its parent runner. Windows cancellation -waits for the command to complete. Do not remove the database while commands -are running. +### Generated files and command ownership -`check` adds formatting, dead-code, and package-metadata freshness checks. -Formatting uses Oxfmt and the committed `.oxfmtrc.json`; generated sources use -the same configuration. Pre-commit formats and lints staged files; pre-push runs -`check:fast`. -`docs:check` builds and validates generated metadata for the current checkout. -The product catalog (`docs/public/product-catalog.json`), portable managed -conformance projections (`docs/verification/managed-conformance-*.json`), and -packaged skill (`skills/`) are ignored generated outputs. `docs:generate` -prepares documentation and managed evidence; `evidence:generate` prepares only -the managed commitment and its runtime/skill dependencies. Edit skill -instructions and references in `skill-src/`; the skill task adds metadata to -the packaged copy without rewriting authored files. The generated manifest -commits to that exact packaged skill bundle. It is a portable projection of -the deterministic managed verifier, not a record of optional real-provider runs. -CI validates these outputs and retains them as artifacts instead of pushing -generated-only commits onto feature branches. Reviewed source metadata such as -`src/generatedPackageMetadata.ts` and `docs/error-contract.schema.json` remains -tracked and checked for freshness. Do not commit ignored generated outputs. -The build-generated product catalog contains documented facts and their provider -identity, rather than full runtime schema hashes. The managed skill contains -instructions and inventory metadata; doctor compares its installed files with -the canonical bundle. Schema-only fixes should not change these outputs or the -skill commitment in the conformance manifest. Runtime schema identity remains -available through doctor and `binary_session`. -Real-provider execution remains uncached; deterministic builds use Turbo. +`docs:generate` prepares documentation and portable managed evidence; +`evidence:generate` prepares only the managed commitment and its runtime/skill +dependencies. The ignored outputs are `docs/public/product-catalog.json`, +`docs/verification/managed-conformance-*.json`, and `skills/`. Edit authored +skill instructions in `skill-src/`. CI validates generated outputs and retains +them as artifacts; do not commit them. Reviewed source metadata, including +`src/generatedPackageMetadata.ts` and `docs/error-contract.schema.json`, remains +tracked and checked for freshness. -Local `npm test` runs every deterministic Vitest project without coverage or -retries. CI runs four coverage shards and merges JUnit and timing reports. -CI cancels superseded PR runs and skips package, Windows, and full test lanes -for documentation-only PRs. Coverage thresholds remain in `vitest.config.ts`. +The packaged skill contains instructions and inventory metadata, not runtime +schema hashes. Its conformance commitment covers that exact bundle and portable +verification; it does not attest optional real-provider runs. Schema-only changes +should not alter that commitment. Doctor and `binary_session` expose runtime +schema identity. -Tests that need a temporary directory must use -`createTestTempDirectory` from `tests/fixtures/temporaryDirectory.ts`. The -helper binds exact-path, awaited cleanup to the current Vitest case, including -failure and timeout completion. Run `npm run verify:test-temp-hygiene` to build -REA, execute the complete suite under a fresh `TMPDIR`, and reject any remaining -REA-owned temporary path. Never add a glob cleanup for shared `/tmp/rea-*` -content. +Build/generation commands hold a SQLite transaction around the entire Turbo +graph, including cache restoration. `.cache/rea-command-locks/` databases identify +locks, not stale files; never remove them while commands run. POSIX cancellation +retains process-group ownership until settlement; Windows waits for completion. +Real-provider execution is uncached. -Set `REA_LOG_LEVEL` to `trace`, `debug`, `info`, `warn`, `error`, `fatal`, or -`silent` to control structured JSON diagnostics. MCP mode defaults to `info` and -always writes logs to stderr so the stdio protocol remains intact. One-shot CLI -logging is opt-in and writes to stdout when a level is configured, preserving -machine-readable command output by default. Request arguments, bridge -authentication tokens, and environment data are redacted. +### Temporary files and diagnostics -Changes that claim real Hopper behavior must also be tested against the -source-owned, digest-bound conformance manifest. The verifier builds the -platform-native fixtures before starting Hopper: +Tests use `createTestTempDirectory` from `tests/fixtures/temporaryDirectory.ts` +for exact-path, awaited cleanup, including failures and timeouts. +`npm run verify:test-temp-hygiene` runs the suite under a fresh `TMPDIR` and +rejects remaining REA-owned paths. Never glob-clean shared `/tmp/rea-*` content. -```bash -npm run verify:hopper -``` +`REA_LOG_LEVEL` selects `trace`, `debug`, `info`, `warn`, `error`, `fatal`, or +`silent`. MCP defaults to `info` on stderr; one-shot CLI logging is opt-in on +stdout. Request arguments, bridge tokens, and environment data are redacted +from diagnostic logs. -On a self-hosted Linux runner with the setup-installed Xvfb dependencies, use: +## Real Hopper changes -```bash -npm run verify:hopper:linux -``` +Run `npm run verify:hopper` on a supported macOS host or +`npm run verify:hopper:linux` on the supported Linux demo runner. These build +native fixtures and verify the installed engine through CLI/MCP; package or +simulated-provider checks do not establish engine behavior. See +[real-toolchain verification](docs/testing.md#end-to-end-integration-and-golden-evidence) +for prerequisites and scope, and [Hopper setup](docs/installation.md#hopper) +for supported hosts and unattended startup. -Set `REA_HOPPER_CONFORMANCE_MANIFEST_PATH` only to verify another source-built -manifest. The normal commands use `build/conformance/manifest.json`; generated -fixtures and manifests remain ignored and must not be committed. - -The macOS and Linux real-Hopper workflows remain separate so a successful mock or package test cannot be reported as platform-runtime proof. Pull requests changing setup, launch, bridge, or Hopper behavior must state which real workflows ran and why either workflow was unavailable. - -Describe the behavior change and verification performed in the pull request. Never commit binaries, Hopper documents, credentials, `dist/`, `node_modules/`, or local planning artifacts. +Use the default `build/conformance/manifest.json` unless explicitly verifying +another source-built manifest with `REA_HOPPER_CONFORMANCE_MANIFEST_PATH`. +Generated fixtures and manifests remain ignored. ## Maintainer release checklist diff --git a/docs/testing.md b/docs/testing.md index c0846b184..9730f027b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,76 +1,36 @@ # Testing REA -Prefer evidence in this order: full end-to-end workflows through the public -CLI or MCP with real production providers and no mocked dependencies, -integration across production data/API boundaries, then golden regressions -from real captured inputs. Keep a focused module test only for a distinct -failure or semantic case that stronger workflows cannot reliably reproduce. -A test's path, compiled imports, or suite name does not establish its depth. +Use this guide when choosing coverage, pruning tests, or running a verification +lane. For commands, jump to [developer commands](#developer-commands); for engine +prerequisites, use [real-toolchain lanes](#real-toolchain-verification-lanes). -Delete tests that only mirror getters, serialization helpers, enum mappings, -fixture helpers, prescribed call sequences, arbitrary counts or snapshots, -or cache object identity without a caller-visible contract. Do not retain a -weaker test merely because it is fast when a stronger workflow already proves -the same claim. Keep format-specific malformed representations and actual -capacity, cleanup, permission and target-identity regressions. -Prefer representative workflows over a Cartesian matrix when rows cross the -same boundary. Retain combinations that exercise a distinct interaction, such as -filtering within a full-output envelope. Keep distinct command handlers, -producer representations, failure reasons, and lifecycle states covered. -Consolidate their shared setup without hiding the inputs or expected evidence. +Prefer real public CLI/MCP workflows, then production-boundary integration, +then goldens captured from real producers. Keep module tests for distinct +failures or semantics that stronger workflows cannot reliably reproduce. +Paths, compiled imports, and suite names do not establish test depth. -Tests are grouped into Vitest projects so ownership, allowed dependencies and -runtime cost are visible from their paths. Before pruning a distinct boundary -regression, identify the replacement scenario and its assertions; passing -success journeys do not replace malformed input, cancellation, permission or -cleanup coverage. Trivial helper checks do not need a replacement. If only -tests consume a production module, trace CLI/MCP and verifier imports, -including imports of compiled files, and remove abandoned scaffolding with its -tests when it has no runtime consumer. +Prune tests that mirror implementation details or duplicate a stronger claim. +Before deleting a distinct regression, identify the replacement scenario and +assertions. Preserve malformed formats, cancellation, cleanup, permissions, +capacity, target identity, and combinations with distinct interactions. +Trivial helper assertions need no replacement. Remove abandoned production +scaffolding only after checking runtime and verifier consumers, including +compiled imports. -When a test expects a `Result` to succeed, throw its error before asserting the -returned value. An `.ok` assertion immediately before the same throwing guard -adds no coverage and hides the typed failure. A removed parser matrix can leave -one golden malformed-input case and a real filesystem lifecycle that proves -configure, update, readback, and removal; an add-only journey does not cover the -whole lifecycle. +Use representative scenarios rather than Cartesian matrices of equivalent +cases. Share setup without hiding inputs or expected evidence. For successful +`Result` values, throw the typed error before asserting the value; a preceding +`.ok` assertion adds no coverage. Protocol fixtures must reject unmodeled +commands and preserve actual producer reply shapes. -Protocol fixtures must model the commands they support and their producer reply -shapes. Reject unmodeled commands instead of returning a generic success; an -empty result is appropriate only for a supported command with no result fields. +Report unavailable authority as a named skip. Await owned cleanup before a +verifier reports success. Native process inspectors are released at Vitest +worker teardown; fork termination does not run Node exit hooks, and per-file +teardown would retire inspectors still needed by other files. -Keep transport-only in-memory MCP sessions in the MCP boundary lane and direct -filesystem workflows in the filesystem boundary lane. Real process-tree capture -belongs in the serial process boundary lane, including captures invoked through -MCP. Report unavailable capture authority as a named skip rather than returning -from the test without assertions. Reserve acceptance paths for journeys -through the compiled public CLI or MCP runtime. Calling a compiled private -workflow or injecting a provider still establishes its narrower integration -claim, even if a directory name calls it acceptance. - -Emit a verifier's final success report only after awaited cleanup. Observe final -process lineage after closing its owned resources. - -Owned JavaScript semantic graphs capture and schema-parse caller input before -returning an iterator. Whole-graph hashing, batched integrity checks and sealing -run through the application cancellation driver; only full completion grants -the private immutable-graph proof. Regression coverage checks canonical IDs, -validation diagnostics, nested caller mutations across yields, cancellation -before result validation and subsequent SDK requests. Single-file parsing, -schema cloning and canonical sorting remain synchronous phases; measure them -separately when assessing cancellation latency on real applications. - -The Vitest runner releases cached native process inspectors during awaited -worker teardown. Fork termination does not run Node's normal exit hooks; a -per-file teardown would instead retire shared inspectors before later files -can use them. - -Measure slow files before removing capacity regressions. Optimize repeated -process startup, fixture construction, and production algorithms when they -dominate runtime. Keep at least one input beyond each formerly failing size or -depth; smaller fixtures do not establish that truncation or stack exhaustion -has been fixed. Record the toolchain, coverage mode, and cache conditions when -comparing durations. +Measure slow cases before pruning capacity coverage. Retain inputs beyond the +formerly failing size/depth and distinguish cold runs, warm builds, coverage, +and toolchain conditions when comparing timings. ## Behavioral depths @@ -93,12 +53,6 @@ registries but do not cross production filesystem, process, socket, or browser b Boundary tests cross one production boundary. Only acceptance tests assemble the complete runtime or invoke the compiled product surface. -Binary session, registry, lazy-client and snapshot module cases live under -`src/application/binary/`. Their composition cases stay in -`tests/composition/analysis-sessions/`; snapshot persistence and actual SDK calls -stay in the filesystem and MCP boundary lanes. The shared injected session fixture -serves several capabilities and remains under `tests/fixtures/`. - Focused immutable builders and recording ports shared by one test family live beside their production owner as `src/**/*.fixture.ts`. They are typechecked with the suite and excluded from package builds; broader runtime and provider @@ -165,29 +119,6 @@ an empty versioned scan or a suffix that only repeats the original path. It runs in macOS CI. -Apple artifact verifiers live in `scripts/verify/apple/`, with the macOS bundle -builder under `scripts/fixtures/apple/` and NIB byte fixtures beside the decoder -in `src/artifacts/apple/`. The npm entrypoints are unchanged. Format-specific -Swift/XIB/asset sources and goldens retain their locations; real Apple workflows -resolve them from the verifier file URL and run in the macOS CI lane. - -Portable native semantics and their tests live in `src/domain/native/`; shared -analyst workflows and service-lane tests live in `src/application/native/`. -Named native contracts live in `src/contracts/native/`. Provider protocol and -host UI tests retain their adapter/boundary lanes, and real verifier command -names remain unchanged. -The existing Apple CI job also runs the host Swift-demangling CLI/MCP regression -suites, including option-like symbols, carriage returns and multiline rejection. - -Process semantics/tests live in `src/domain/process/`; PTY capture implementation -and forked helper tests live in `src/process/capture/`. Evidence projection and -file workflows live in `src/application/process/`; producer-backed Evidence/host -cases run in the serial `tests/boundary/process/` lane. Installed-package probes -load the compiled capture capability owner, including the missing-optional-module -case. Real capture tests preserve actual descendant and cleanup checks. -The existing Apple job also exercises the relocated filesystem snapshot identity, -cancellation and descriptor cleanup regressions on macOS. - Prepare the native inspector before cases that measure producer output or exit behavior; keep startup deadlines and cancellation in distinct cases. Run real process-capture verification separately from package or build checks. On macOS, @@ -198,8 +129,7 @@ MCP SDK transport tests with recording providers remain integration tests. They are useful for schema drift and failure projection but do not prove that Hopper, Ghidra or another substituted engine works. `verify:package` proves packaging/install behavior and fake-provider integration; use the corresponding -real-provider lanes for engine claims. Packed-bridge checks verify shipped files -and Python syntax without deleted mock fixtures or source-spelling assertions. +real-provider lanes for engine claims. Packed-bridge checks verify shipped files and Python syntax. Real Apple dispatch and Interface Builder verifiers currently prove format integration through production readers. @@ -274,7 +204,7 @@ Do not call handcrafted utility output or synthetic binary builders real-data goldens. Keep unsupported binary layouts and malformed boundaries as targeted regressions until a real fixture establishes equivalent coverage. -`verify:browser` exercises source-map failure isolation and expanded-output limits through the compiled CLI and stdio MCP with real Chrome. It also submits five 2 MiB source-map annotations, checks retained script identities and explicit map omissions, and closes its owned fixture target. These public workflows replace redundant metadata-admission assertions; replacement and document-reset boundaries remain focused producer regressions. +`verify:browser` exercises source-map failure isolation and expanded-output limits through the compiled CLI and stdio MCP with real Chrome. It also submits five 2 MiB source-map annotations, checks retained script identities and explicit map omissions, and closes its owned fixture target. Replacement and document-reset behavior has separate producer-boundary coverage. `verify:browser` also captures a source-owned noise canvas as a real PNG above 8 MiB through the CLI and stdio MCP, with complete byte/digest parity and real PNG @@ -399,9 +329,7 @@ Instruction inspection and containing-function lookup also agree across hexadecimal case, leading zeros, and encoded default address-space spellings. The same source-acquisition workflow exercises missing and directory-replaced inputs, plus real read-permission denial on a non-root host. Root runs report -that permission-denial check as unverified. A focused filesystem integration -check retains selected-platform routing and exclusive creation; two copy/digest -checks duplicated by the real workflow have been removed. +that permission-denial check as unverified. Filesystem integration separately checks selected-platform routing and exclusive creation. Namespace annotation probes compile a separate host C fixture with C++ ABI symbols, avoiding a C++ runtime prerequisite. Real Ghidra demangling supplies duplicate leaf names in two top-level namespaces and a nested namespace. The @@ -416,8 +344,7 @@ Successful-result and oversized-error delivery constraints must identify their successfully retained Evidence records; export must recover every source byte, complete annotation and original error diagnostic, with CLI parity -and an unchanged executable. The focused formatter check retains only the -separate case where recording was not acknowledged. +and an unchanged executable. Formatter integration separately checks unacknowledged Evidence recording. Long ordinary procedure names and encoded address-space selectors must produce normal validation errors without exhausting Java's regex stack or losing the private bridge connection. Each rejection is followed by a real provider lookup; @@ -457,14 +384,9 @@ the CLI and stdio MCP, including special filenames, unresolved discovery locations, and independently resolved loaded scripts. Double-quote filenames are tested on POSIX only because Windows does not support them. -Inspector adapters live in `src/inspector/`, with loopback fixtures under -`tests/fixtures/inspector/` and forked producer boundaries under -`tests/boundary/inspector/`. The real lane is owned by -`scripts/verify/inspector/runtime-observation.mjs` and -`tests/conformance/inspector/`. Browser and Inspector deliberately share the -existing browser CDP transport/value and file-location helpers. Node fixture -success proves this Inspector workflow on the tested host; it does not prove -Electron GUI behavior or another engine. +Node Inspector verification does not establish Electron GUI or other engine +behavior. Browser and Inspector share CDP transport/value and file-location +helpers; their producer workflows remain distinct. ## Android APK analysis @@ -486,14 +408,6 @@ See [Android analysis](android-analysis.md) for boundaries and resource budgets. Authenticated IPA and macOS application inventory projection is documented in [Apple application analysis](apple-application-analysis.md). -The lane and owned-process cancellation helper live in `scripts/verify/android/`. -The explicit downloader and fixed manifest live in `scripts/fixtures/android/`; -their default remains repository-root `_reference/apk-integration/`. Producer -fixtures live in `tests/fixtures/android/`, boundary cases in -`tests/boundary/android/`, and inventory projection composition cases in -`tests/composition/android/`. Real engine success and synthetic protocol success -are separate proof levels. - Synthetic producer regressions run independently: ```sh @@ -627,13 +541,6 @@ installation, CLI/MCP discovery, target-free analysis, configuration backups/recovery, Evidence and owned lifecycle; Inspector checks execute source-owned loopback targets and special filename cases. -Each native package host runs package and Inspector checks on the same runner -after a single dependency installation. macOS uses one OS version with one -native baseline job per architecture. Windows runs Inspector with its curated -capability/package checks before switching Node versions for directory-identity -regressions. Inspector steps retain a ten-minute deadline; Apple artifact checks -retain their own macOS 15 arm64 job for Xcode-dependent workflows. - These native baseline checks complement the Linux source-test shards and the separate Apple-artifact and real-provider lanes. Actual Hopper, Ghidra, IDA, browser and managed-tool claims require their corresponding verification lanes. @@ -703,23 +610,15 @@ broad changes or diagnosing CI, rather than after every edit. Package/install changes additionally need package verification; provider changes need actual provider evidence. -Each Vitest project uses up to two workers, bounded by available host parallelism. -Default-group projects can run together. Only `process-boundary` runs in the -later sequence group and serializes its files because process-tree observations -share host sampling resources. Tests that launch the real process harness belong -in `tests/boundary/process/`, including CLI command and environment tests. -Acceptance and process-global files retain isolated -forks but are not serialized; isolation does not imply serial scheduling. CI uses -the same per-project worker bound. -The pure domain/contracts and recording-port service projects share one worker -module context because their tests own no mutable runtime resources. MCP -boundary files also share the immutable server module graph while creating and -closing independent in-memory sessions. Adapter, composition, acceptance, -process-global, and other boundary projects retain per-file isolation. -Build and documentation writers use checkout-local locks for their respective -output files. `npm test` delegates its build to the build lock; the Vitest suite -does not hold a test-command lock. `check:pr` runs its test task before starting -generated-document validation. +Vitest projects use up to two workers, bounded by host parallelism. +`process-boundary` runs later with serial files because process-tree sampling +shares host resources. Acceptance and process-global cases use isolated forks +without serial scheduling. Pure domain/service and MCP boundary projects share +immutable module graphs; each MCP session still owns its resources. Other +projects retain per-file isolation. See `vitest.config.ts` for current settings. + +Build/documentation writers hold checkout-local output locks. Tests do not +hold a broad command lock; `check:pr` finishes tests before document validation. Vitest and Node persistent compile caches are deliberately not enabled by default. To evaluate repeated local runs, opt in for both cold and warm @@ -735,13 +634,9 @@ instrumentation remains equivalent. ## Coverage and timing -CI owns coverage. The aggregate floors are 65% statements, 60% branches, 60% -functions, and 68% lines. `src/domain/**` must reach 80% statements, 75% -branches, 75% functions, and 80% lines. `src/contracts/**` must reach 85% -statements, 80% branches, 80% functions, and 85% lines. Thresholds are -glob-specific rather than per-file and are never updated automatically. -Coverage does not replace named boundary, acceptance, or real-provider scenario -matrices. +CI owns coverage; aggregate and domain/contract thresholds are maintained in +`vitest.config.ts`. They are glob-specific and never updated automatically. +Coverage does not replace named boundary or real-provider scenarios. CI runs four native Vitest shards without retries. Each shard emits a blob report; the merge job produces aggregate coverage plus JUnit and JSON timing @@ -815,12 +710,6 @@ unknown chunks, depth limits and extracted child digests. The optional Neither optional toolchain is a base-lane prerequisite. See [firmware analysis](firmware-analysis.md) for limits and unverified formats. -The real entrypoint is `scripts/verify/firmware/analysis.mjs`; the fixture runner -and unchanged Python producer belong together in `scripts/fixtures/firmware/`. -Producer fixtures and boundaries remain in `tests/fixtures/firmware/` and -`tests/boundary/firmware/`. Source-fixture generation proves the runner and -independent oracle; actual Binwalk/Unblob CLI/MCP proof requires selected tools. - ### JavaScript source recovery Build once with `npm run build:cached`, then run `npm run verify:javascript:recovery`. diff --git a/docs/tool-design.md b/docs/tool-design.md index ed8c09aaf..934722850 100644 --- a/docs/tool-design.md +++ b/docs/tool-design.md @@ -1,112 +1,87 @@ # MCP tool design -Design tools around analyst tasks. A provider API is an implementation detail; -expose it directly when it gives agents a useful, reusable capability that -cannot be expressed through an existing contract. Do not impose caller-facing -limits merely to make work fit an assumed agent budget. Keep real input-format, -protocol, authority, and resource-safety constraints, and report their effects. - -## Choose the tool shape - -| Shape | Use it for | Contract should return | -| --------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `inspect` | Facts about one explicit target, address, object, or resource | Relevant fields, source locations, and facet-level availability | -| `search` / `list` | Finding candidate targets or entities | Stable ordering and useful result context; expose pagination when the result format or caller's query needs it | -| `trace` | Relationships across code, metadata, UI resources, or observations | Typed edges, supporting evidence, and unresolved paths; identify any genuine traversal boundary | -| `compare` | Two explicitly identified artifacts, versions, or evidence sets | Paired identity, comparable coverage, and deltas with evidence | -| `workflow` | A distinct analyst outcome that benefits from composition inside REA | A useful inline result, contributing evidence, and partial/unavailable facets | -| `observe` / `capture` | A question that requires runtime behavior | Required authority, launch/attach behavior, real operational constraints, lifecycle, and cleanup status | - -These are task shapes, not required prefixes. Name a tool for the action and -object agents reason about; keep the name distinct from nearby alternatives. - -## Prefer primitives; compose workflows - -Let agents compose experiments with ordinary commands, scripts, and local -fixture servers. A custom orchestration language, replay engine, or separate -prepare/execute plan needs an observed requirement those primitives cannot -satisfy. Expose useful inspection directly; a plan-only tool without an executor -does not establish runtime behavior. - -Start with a primitive when one call can report a reusable fact about one -identified object or relationship, such as an instruction decode, a type -layout, a reference, a dispatch target, or a resource graph. The same primitive -should be useful across different applications or analyst questions. A -format-specific decoder can still be a primitive when it describes a reusable -format rather than one application's product behavior. - -Add a workflow when repeated analysis shows that callers need the same -multi-source result and REA can join the evidence without hiding important -choices or uncertainty. A useful check is whether the workflow remains -meaningful for different applications that share the relevant evidence types. -If its purpose depends on one application's business rules or product concepts, -keep that interpretation outside the general tool contract and expose the -underlying evidence through reusable primitives. - ## Decide whether to add a tool -1. State the user intent and the smallest result that answers it. -2. Inspect the canonical tool contracts, current provider capabilities, and - representative CLI/MCP traces. Record the nearest competing tool. -3. Extend an existing contract when the intent and result are the same. Add a - batch or composed workflow when it materially improves a demonstrated task; - do not force agents through extra calls or collapse distinct tasks into one - tool. Add a tool when it answers a distinct analyst question or has a - materially different authority or result contract. -4. Keep public tool names and result semantics provider-neutral. Put engine- - specific parsing and protocol handling in adapters. Advertise exact support - per provider; do not create parallel tools just because engines differ. -5. Keep prompts optional and concise. They may point out useful tools, but must - not prescribe a call sequence when the task can be answered directly. +Design around the analyst question. Inspect the current canonical contracts, +provider capabilities, and nearest existing tool before changing the surface. +Extend a tool when intent and result contract match; add one for a distinct +outcome or materially different authority. Public names and semantics remain +provider-neutral, with exact coverage reported per provider. -Avoid opaque mode flags and mega-tools that combine unrelated discovery, -execution, and mutation. Prefer a useful direct tool call over a tool sequence -or model-authored loop when one call can answer the question. +Keep the catalog complete; report capability/session availability instead of +truncating schemas. Serialized bytes alone do not establish agent usability. + +## Choose the tool shape + +| Shape | Use it for | Result | +| --------------------- | ------------------------------------------- | ------------------------------------------------------------------------- | +| `inspect` | Facts about one target, object, or resource | Relevant fields, locations, and facet availability | +| `search` / `list` | Candidate discovery | Stable ordering and context; pagination when the query or format needs it | +| `trace` | Relationships across evidence | Typed edges, supporting facts, and unresolved paths | +| `compare` | Explicitly paired artifacts or observations | Identity, comparable coverage, and supported deltas | +| `workflow` | A recurring outcome needing composition | Inline answer, contributing evidence, and partial facets | +| `observe` / `capture` | Runtime behavior | Authority, launch/attach effects, lifecycle, and cleanup status | + +These are task shapes, not mandatory prefixes. Name tools for the action and +object callers reason about. Avoid unrelated discovery/execution/mutation modes +inside one tool. + +## Prefer primitives; compose workflows + +A primitive reports a reusable fact about an identified object or relationship. +A format-specific decoder qualifies; one application's business interpretation +belongs outside the general contract. Expose provider APIs when they add a +useful capability that existing tools cannot express. + +Compose a workflow when repeated use demonstrates a multi-source outcome REA +can join without hiding caller choices or uncertainty. Batch homogeneous reads +when that removes repeated work while preserving per-item outcomes. Keep prompts +optional and avoid prescribing call sequences that a direct tool can replace. + +Agents can compose experiments with ordinary commands, scripts, and local +fixture servers. Custom orchestration languages, replay engines, or separate +prepare/execute plans need an observed requirement those primitives cannot +satisfy. A plan without execution does not establish runtime behavior. ## Define the contract -- Use strict object inputs with explicit required fields and enums. Add numeric - bounds only when the format, protocol, authority, or a measured resource - constraint requires them. -- Return complete results by default. Make real pagination, truncation, partial - failure, cancellation, and unavailable states explicit. Missing evidence is - unknown, not empty or false. -- Return task-oriented results inline with artifact identity, provider/version, - addresses or resource paths, Evidence references, confidence, and relevant - limitations. Do not require agents to fetch a resource or dereference an - opaque Evidence link to understand a tool result. -- Separate observed facts from derived and inferred edges. Cite the evidence - supporting every important relationship; preserve unresolved edges. -- Declare read-only, mutation, process, filesystem, network, and UI effects - truthfully in the contract and enforce the target and lifecycle named in the - request. -- Keep provider-specific types out of provider-neutral domain and application - layers. Normalize supported provider results without implying equal coverage. +- Use strict inputs with explicit target identity and required fields. Preserve + meaningful target, action, capture, and output choices; remove ignored options + and repeated permission declarations. +- Return complete evidence inline, with artifact/provider identity, source + locations, Evidence references, and relevant confidence and limitations. + Missing coverage is unknown, not absence. Avoid extra lookups solely to + understand the answer or its provenance. +- Keep observed, derived, and inferred relationships distinct. Preserve + unresolved edges and partial provider facts instead of requiring every + provider to supply the same metadata. +- Declare process, filesystem, network, UI, and mutation effects truthfully; + enforce the requested target and lifecycle. +- Add limits only for real format, protocol, authority, or measured resource + constraints. Report pagination, truncation, cancellation, and partial failure. + An assumed agent budget is insufficient justification for a limit. ## Implement and evaluate -- Put shared user workflows in the application layer; keep MCP translation in - the server adapter and CLI behavior aligned with the same workflow. Share - Evidence provenance, unknown projection, and eligible snapshot binding through - application/session owners. Matching result payloads alone do not establish - equivalent retention or replay behavior. -- Derive each facet's coverage from examined records, unsupported representations, - and exhaustiveness. Keep issues structured until presentation; do not select a - facet by matching diagnostic prose or infer completeness from an empty failure - list. Preserve available observations independently of cleanup success. -- Measure the resource consumed before choosing a limit. Value alternatives, - retained records, trace-frame products, output bytes, and temporary-file growth - need different accounting. Enforce a justified budget before the costly step - and report its effect; an input-byte or graph-node cap does not bound every stage. -- Update the canonical contract inventory, output schemas, examples, generated - catalog, and relevant docs together. -- Verify valid, malformed, boundary, unavailable, cancellation, and partial - results at the owning boundaries. Use real-provider checks for claims that - depend on external analysis engines. -- Evaluate representative broad and direct task prompts on the intended MCP - host when tool selection is the question. Record the host, model-facing tool - catalog, selected tool, arguments, errors, retries, and task outcome. - Schema validity or word-overlap heuristics do not prove discoverability. +Put provider protocols/parsing in adapters and shared CLI/MCP workflows in the +application layer. Share Evidence provenance, unknown projection, and session +retention semantics; matching payloads alone do not establish parity. -See [mcp-contracts.md](mcp-contracts.md) for shipped runtime behavior and -[testing.md](testing.md) for test boundaries and verification lanes. +Measure the resource before choosing a budget and enforce it before the costly +step. Account for value alternatives, trace-frame products, retained records, +serialization expansion, and temporary-file growth separately. Derive facet +completeness from examined records and exhaustiveness, rather than diagnostic +prose or an empty failure list. Preserve observations independently of cleanup +success. + +Update canonical contracts, output schemas, examples, generated artifacts, and +relevant docs together. Verify converted advertised schemas and success, +malformed, unavailable, cancellation, and partial outcomes through affected +consumers. Real-engine claims require the matching provider lane; see +[testing.md](testing.md). + +When discoverability changes, evaluate representative broad, direct, and negative +tasks on the intended host. Record host/model/catalog, selected tools, arguments, +errors, retries, and task outcomes. Schema validity and keyword heuristics do not +establish successful tool selection. See [mcp-contracts.md](mcp-contracts.md) for +shipped runtime behavior. From 7738c1f6a9ccf1ec9868ef832f154abe9ba5eebd Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:30:02 +0800 Subject: [PATCH 104/189] docs: add repository-local REA tool design skill --- .agents/skills/rea-tool-design/SKILL.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .agents/skills/rea-tool-design/SKILL.md diff --git a/.agents/skills/rea-tool-design/SKILL.md b/.agents/skills/rea-tool-design/SKILL.md new file mode 100644 index 000000000..f4ba7894e --- /dev/null +++ b/.agents/skills/rea-tool-design/SKILL.md @@ -0,0 +1,20 @@ +--- +name: rea-tool-design +description: Design or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. +--- + +# REA tool design + +Use the [tool-design guide](../../../docs/tool-design.md) for tool boundaries, +contract semantics, provider ownership, and discoverability. Inspect the current +contract and nearest existing tool relevant to the analyst question; source, +documentation, and live catalogs may describe different versions. + +For a design request, return the proposed boundary, input/result shape, Evidence +semantics, nearest alternative, and verification approach. Implement when +requested, preserving the user's scope and existing authorization. + +For implementation or verification, consult [testing](../../../docs/testing.md) +for the affected consumer and provider lanes, and +[contributing](../../../CONTRIBUTING.md) for generated-file ownership. Read +provider/workflow guides only as the task requires. From 7a0c80085128e6329ca2e4f54f3539f3245c57d1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:41:45 +0800 Subject: [PATCH 105/189] docs: remove retired architecture and migration artifacts --- CONTRIBUTING.md | 9 +- docs/.vitepress/config.ts | 3 +- ...rovider-selection-and-analysis-profiles.md | 572 ------------------ ...controlled-replay-authority-and-sandbox.md | 551 ----------------- ...ged-code-evidence-and-provider-boundary.md | 452 -------------- docs/adr/README.md | 11 - docs/capability-migration.md | 477 --------------- docs/cli.md | 2 +- docs/ghidra-provider.md | 72 +++ docs/managed-code-analysis.md | 274 ++------- docs/provider-evaluation.md | 219 ------- docs/roadmap.md | 144 +---- 12 files changed, 153 insertions(+), 2633 deletions(-) delete mode 100644 docs/adr/0001-provider-selection-and-analysis-profiles.md delete mode 100644 docs/adr/0002-controlled-replay-authority-and-sandbox.md delete mode 100644 docs/adr/0003-managed-code-evidence-and-provider-boundary.md delete mode 100644 docs/adr/README.md delete mode 100644 docs/capability-migration.md create mode 100644 docs/ghidra-provider.md delete mode 100644 docs/provider-evaluation.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c60c1e9e2..07c71c4c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,9 +10,12 @@ and maintenance cost. Keep cosmetic polish with useful fixes; confusing or incorrect user instructions warrant standalone corrections. Collect other cosmetic-only suggestions in an issue rather than separate PRs. -For capability organization and provider composition, follow the incremental -[migration guide](docs/capability-migration.md). Run `npm run verify:test-discovery` -after adding or moving tests. +For capability organization and provider composition, use the +[architecture map](docs/architecture.mermaid). Production factories in +`src/composition/` construct fresh providers without starting engines or acquiring +targets; optional adapter failures must preserve successful peers. Run +`npm run verify:test-discovery` after adding or moving tests. Resolved import +boundaries are checked by `npm run verify:module-boundaries`, included in lint. When adding or changing an MCP tool, follow the [tool design guide](docs/tool-design.md) and preserve the canonical contracts and generated catalog. diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 314362009..e1c184993 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -55,7 +55,7 @@ export default defineConfig({ { text: "Ghidra on Windows", link: "/windows-ghidra-p0" }, { text: "Ghidra DOS analysis", link: "/ghidra-dos" }, { text: "Ghidra NativeAOT", link: "/ghidra-nativeaot" }, - { text: "Provider evaluation", link: "/provider-evaluation" }, + { text: "Ghidra semantics", link: "/ghidra-provider" }, ], }, { @@ -66,7 +66,6 @@ export default defineConfig({ { text: "Tool design", link: "/tool-design" }, { text: "Testing", link: "/testing" }, { text: "Releasing", link: "/releasing" }, - { text: "Architecture decisions", link: "/adr/README" }, ], }, ], diff --git a/docs/adr/0001-provider-selection-and-analysis-profiles.md b/docs/adr/0001-provider-selection-and-analysis-profiles.md deleted file mode 100644 index 588fb3ebc..000000000 --- a/docs/adr/0001-provider-selection-and-analysis-profiles.md +++ /dev/null @@ -1,572 +0,0 @@ -# ADR-0001: Provider selection and analysis profiles - -- Status: Accepted -- Date: 2026-07-15 -- Implementation status: The provider registry, deterministic selection, - target binding, analysis-profile commitment, and snapshot/Evidence migration - are implemented. Ghidra discovery, target/profile resolution, doctor checks, - the private headless-session foundation, thirteen read-only inventory/load-image - capabilities, and twelve function-analysis capabilities are implemented with - real cross-format conformance. Linux/macOS also supports atomic session - function annotations; experimental Windows x64 P0 uses bundled native controls - and admits only the 25 read-only operations. See the - [release boundary](../installation.md#released-package-and-main). - -## Context - -Before this decision, REA composed the artifact, native macOS, and Hopper -providers with `CompositeProvider`. That class intentionally requires every -operation to have one route. Hopper and Ghidra will both implement the deep -static-analysis operation family, so putting both into that composite would -either fail at construction or make array order an undeclared selection policy. - -The active `BinarySession` also owned one composite client. `open_binary` had no -provider selector, and the domain `BinaryTarget` contained Hopper loader -arguments. Analysis snapshot v1 committed those loader arguments and each -cached entry's provider identity, but it did not commit the selected analysis -engine, engine version, or complete analysis configuration. Two analyses of the -same bytes could therefore disagree because of language, compiler, loader, -analyzer, or provider-version differences while appearing target-compatible. - -The decision addressed the earlier representations of -[`CompositeProvider`](https://github.com/morluto/rea/blob/main/src/application/binary/CompositeProvider.ts), -[runtime composition](https://github.com/morluto/rea/blob/main/src/composition/binary.ts), -[`BinarySession`](https://github.com/morluto/rea/blob/main/src/application/binary/BinarySession.ts), -[`BinaryTarget`](https://github.com/morluto/rea/blob/main/src/domain/binaryTarget.ts), -[analysis snapshot](https://github.com/morluto/rea/blob/main/src/domain/analysisSnapshot.ts), and -[session lifecycle inputs](https://github.com/morluto/rea/blob/main/src/contracts/sessionLifecycleInputs.ts). - -The next deep provider must not weaken the existing product invariants: - -- stable provider-neutral CLI and MCP tool names; -- exact provenance and explicit unavailable or degraded capabilities; -- CLI and MCP parity; -- no silent provider fallback; -- provider-specific code outside the domain and application models; -- local, actionable diagnostics with only genuine secrets redacted; and -- snapshot reuse only when semantic analysis inputs are identical. - -## Decision drivers - -1. Hopper and Ghidra need to declare overlapping operations without ambiguous - dispatch. -2. A target must have one explainable deep-analysis producer for its lifetime. -3. Target-free discovery must remain useful and must not start an analysis - process. -4. Existing Hopper-only configurations must keep working when no selector is - supplied. -5. Adding a second installed provider must not silently change results. -6. Snapshot and Evidence compatibility must include every setting that can - materially change analysis. -7. Provider-specific open settings must not leak into `BinaryTarget` or become - generic application fields. - -## Terminology - -- **Deep provider**: an engine such as Hopper or Ghidra that implements the - overlapping static-analysis operation family. -- **Auxiliary provider**: a provider with a disjoint operation family, such as - artifact inventory or native macOS inspection. -- **Candidate**: a registered deep provider before target selection. -- **Binding**: the selected deep provider and analysis profile attached to one - active target. -- **Analysis profile**: a canonical commitment to the selected provider, - provider version, and normalized semantic analysis settings. -- **Available**: the adapter and its required local runtime can be used on this - host. -- **Supported**: the candidate accepts the parsed target and supplied open - options. Availability and target support are separate observations. - -## Decision - -### 1. Separate disjoint composition from overlapping selection - -`CompositeProvider` remains the mechanism for operation families whose routes -are disjoint. It must continue rejecting duplicate operation declarations. It -must not acquire priority, racing, fallback, or provider-selection behavior. - -A new `AnalysisProviderRegistry` owns the configured deep-provider candidates. -Provider IDs are unique; duplicate IDs are a configuration error. The registry -may hold multiple candidates that declare the same operation. It performs -candidate discovery, target-support evaluation, option parsing, profile -resolution, and selection, but it does not choose a different provider for each -request. - -After selection, the session composes exactly one bound deep provider with the -auxiliary disjoint families: - -```text - target-free discovery - | - AnalysisProviderRegistry - / \ - Hopper Ghidra - \ / - one selected binding - | - +-------------------------+-------------------------+ - | | | - selected deep family artifact family native family - +-------------------------+-------------------------+ - | - BinarySession -``` - -An auxiliary operation continues to report its actual auxiliary provider as -provenance. A deep operation always reports the provider in the active binding. -The synthetic composite identity is never evidence that two engines jointly -produced one observation. - -Operation ownership is fixed by family: - -| Operation family | Executor | -| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | -| Deep direct operations and provider-native function analysis | The one bound Hopper or Ghidra provider | -| Application-enhanced deep workflows | Application composition over the bound provider's declared operations | -| Native macOS inspection | The disjoint native provider | -| Artifact inventory and extraction | The disjoint artifact provider | -| Browser and Electron observation | Their independently authorized CDP providers; they do not participate in deep-provider selection | -| Session lifecycle, Evidence, comparisons, and reconstruction | The application/session layer using the exact provider provenance recorded by their source operations | - -Selecting a deep provider selects the whole deep family. If that provider marks -an operation unavailable, REA returns the unavailability; it does not borrow -that one operation from another deep provider. Application-enhanced workflows -run only when the bound provider supplies their declared dependencies. - -### 2. Discover candidates without launching analysis - -Each registered candidate exposes three bounded adapter-owned observations: - -1. identity and declared capability descriptors; -2. host availability, including an actionable rejection when unavailable; and -3. target support plus normalized profile resolution when a target is known. - -Target-free discovery may inspect configuration, manifests, executable -metadata, and documented version files. It must not import a target, create a -project, open a GUI, or start the long-lived analysis process. Any short-lived -version probe added later must be explicitly bounded and truthfully declared as -a process effect. - -Candidate output is sorted by provider ID for determinism. Sort order is not -selection priority. Availability and support use stable codes plus a human -diagnostic: - -| Code | Meaning | -| ---------------------------- | --------------------------------------------------------------- | -| `not_configured` | Required provider location or configuration is absent | -| `executable_missing` | The configured provider entry point is missing or not runnable | -| `runtime_missing` | A required provider runtime, such as Java, is unavailable | -| `unsupported_host` | The host platform or architecture is unsupported | -| `unsupported_version` | The discovered provider or runtime version is unsupported | -| `target_kind_unsupported` | The provider does not accept this target kind | -| `target_format_unsupported` | The provider does not accept this target format | -| `architecture_unsupported` | The selected target architecture is unsupported | -| `target_role_unsupported` | The provider rejects this executable image role | -| `managed_target_unsupported` | The provider does not admit managed code through this deep path | -| `open_options_invalid` | The selected adapter rejected its open options | -| `version_unresolved` | A concrete analysis-engine version could not be committed | - -Diagnostics retain useful local paths, observed versions, architectures, and -mismatch details. Credentials, authorization headers, license secrets, and -other genuine secrets remain redacted. - -### 3. Use one deterministic selection algorithm - -The caller-visible selectors are: - -- MCP `open_binary.provider_id`; -- `rea ... --provider ` on every one-shot command that needs - deep analysis; and -- `REA_ANALYSIS_PROVIDER=`, defaulting to `auto`. - -The literal value `auto` is reserved and cannot be a provider ID. Precedence is -request or CLI flag, then environment configuration, then the default `auto`. -An explicit request for `auto` overrides a concrete environment preference and -re-enters automatic selection. - -Selection occurs after provider-neutral target parsing and before a deep client -is created: - -1. A concrete requested provider ID must exist, be available, support the - target, accept its options, and resolve a concrete version and profile. Any - failure returns a typed selection error; another provider is never tried. -2. `auto` filters candidates by availability and target support. -3. Exactly one usable candidate is selected with source - `auto-single-candidate`. -4. More than one usable candidate is an `ambiguous` selection error. The - diagnostic lists the candidates and asks for `provider_id`, `--provider`, or - `REA_ANALYSIS_PROVIDER`. REA does not prefer Hopper, Ghidra, registration - order, the fastest startup, or the first health response. -5. When no deep candidate is usable, an automatic open may still establish an - unbound target so disjoint artifact or native operations remain available. - Deep operations are then explicitly unavailable with the candidate - rejections. A concrete request, or a concrete environment preference for a - deep-eligible target, remains a hard requirement and fails instead of - becoming unbound. -6. A target that no deep adapter declares support for, such as an artifact-only - target, is `not_applicable` rather than a failed deep analysis. Supplying a - concrete provider in that open request is still an actionable unsupported- - target error. A global environment preference does not make an artifact-only - target require a deep provider. - -This preserves target opening for non-Hopper capabilities on hosts without a -deep engine while ensuring that installing a second usable deep engine never -changes analysis silently. - -### 4. Bind once and never fail over mid-session - -An active deep binding contains: - -```text -canonical target identity -selected provider identity and concrete version -selection source: request | environment | auto-single-candidate -analysis profile commitment -owned provider client, once started -``` - -The binding is immutable until `close_binary` or an explicit open/switch -transaction. Provider client creation may remain lazy, but laziness cannot -change which provider was selected. - -- Opening the same canonical target without a new selector keeps the existing - binding. -- Opening the same target with the same provider and profile is idempotent. -- A different explicit provider or a profile-changing option is a real switch: - drain active calls, close owned resources, resolve the new binding, and start - it as one serialized transaction. -- If a switch fails, restore the prior target and binding on a best-effort - transactional path and return the original switch error. -- Provider process exit, timeout, cancellation, capability failure, or adapter - error never triggers fallback. The binding stays visible and unavailable - until the caller explicitly switches or closes it. -- A snapshot never chooses or changes the provider. Selection happens first; - snapshot compatibility is checked against the resulting binding. - -Calls already admitted to one binding complete or cancel against that binding. -No request can cross a concurrent target or provider transition. - -### 5. Keep provider open options adapter-owned - -`BinaryTarget` retains only provider-neutral source identity and classification: -canonical path, source digest, generic kind and format, selected architecture, -and available architectures. Hopper loader arguments leave the domain model. -Provider-owned databases use a generic analysis-database classification; their -adapter determines support. A `.hop` analysis database is therefore accepted only -by Hopper without teaching the domain how to open it. Ghidra v1 continues to use -private temporary projects and does not open user projects. - -The generic transport may carry one bounded JSON `provider_options` object. -Only the selected adapter parses its keys and reports `open_options_invalid` at -that boundary. If this object is exposed over MCP, the CLI parity surface is -`--provider-options-json` with the same JSON schema and limits. Unknown keys, -wrong-provider options, excessive depth or size, and non-JSON values fail -closed. - -Environment settings that are inherently adapter-specific, such as the Hopper -launcher or future Ghidra installation path, remain in adapter configuration. -They do not become `BinaryTarget` fields. The application layer transports an -opaque, already-bounded JSON value and the generic commitment described below; -it does not interpret Hopper or Ghidra option names. - -### 6. Commit a canonical analysis profile - -Before creating a deep client, the selected adapter normalizes every semantic -input that can affect analysis. Examples include Hopper loader selection and -architecture flags, or Ghidra language ID, compiler specification, import mode, -analyzer set, and analyzer options. Defaults are made explicit, unordered sets -are sorted, and implicit host-dependent choices are resolved. - -The adapter returns this provider-neutral envelope: - -```json -{ - "provider": { "id": "ghidra", "version": "" }, - "parameters": {}, - "digest": "" -} -``` - -`parameters` is bounded JSON interpreted only by that provider adapter. It -contains analysis semantics, not credentials, authorization data, temporary -paths, installation paths, process IDs, timestamps, or other incidental host -state. The generic domain validates the envelope and digest but treats the -parameters as opaque data. - -A selected deep binding requires a concrete provider version. If the adapter -cannot determine it, the candidate is unavailable with `version_unresolved`; -REA does not persist a cache that merely commits `null` or "whatever is -installed". Provider identity, normalized parameters, or provider version -changes produce a different digest. - -The same target, configuration, and provider must resolve the same profile over -CLI and MCP. Profile resolution must be side-effect-free and complete before -the provider imports the target. - -### 7. Make snapshots provider- and profile-exact - -Analysis snapshots replace Hopper loader arguments with an explicit binding -commitment: - -```text -target: digest + generic format/kind + selected architecture -binding: provider identity + analysis profile commitment -entries: exact immutable queries -evidence_bundle: retained Evidence records -``` - -The snapshot target identity, canonical snapshot content digest, and every -query ID commit the provider ID, concrete provider version, and profile digest. -A cached entry is reusable only when all of the following match exactly: - -- target digest, generic format and kind, and selected architecture; -- provider ID and provider version; -- profile digest; -- operation and canonical parameters; and -- the existing cacheability and immutability rules. - -Provider or profile switches select a separate cache partition and cannot reuse -entries from the previous binding. Auxiliary operations are cacheable only if -their provider defines an equivalent explicit profile commitment; otherwise -they remain Evidence but not snapshot entries. - -Snapshot v1 cannot be parsed as the current snapshot format. Its `loader_args` -cannot prove which engine version, defaults, or analyzer settings produced the -entries, so snapshots must be recaptured before they can be used as a cache. -An embedded Evidence bundle can still be imported separately through the -Evidence import flow; it is never promoted into an analysis cache. - -### 8. Commit concrete or explicitly unknown analysis profiles in Evidence - -Every Evidence record includes `analysis_profile`, either the canonical profile -envelope above or `null` when no profile was observed. Deep-analysis observations -commit the resolved provider ID, version, and effective configuration in this -profile. The field participates in the Evidence semantic ID. - -An explicitly unknown profile can be displayed and cited, but cannot establish -profile compatibility, seed snapshot replay, or support an "unchanged" -conclusion that depends on identical analysis semantics. Snapshot query entries -must have matching profile-bound Evidence; imports reject missing or mismatched -observations instead of silently dropping query entries. Both `entries` and -`workflow_entries` are required arrays, including when empty. - -Different providers or profile digests are never snapshot-compatible. A -derived comparison may compare cross-provider normalized facts only when its -own contract explicitly defines that semantic comparison. Exact pseudocode, -provider text, or provider-specific metadata is not treated as equivalent. A -missing or incompatible profile yields unknown or incompatible, never equal. - -### 9. Expose selection truth in status and diagnostics - -`binary_session`, `rea providers`, and `rea capabilities` expose the same -candidate and binding model. The target-free form does not start providers and -uses `unknown` for target support: - -```json -{ - "analysis_provider_binding": null, - "analysis_provider_candidates": [ - { - "provider": { - "id": "hopper", - "name": "Hopper Disassembler", - "version": "" - }, - "availability": { - "status": "available", - "code": null, - "reason": null, - "diagnostics": {} - }, - "target_support": { - "status": "unknown", - "code": null, - "reason": "No target is open." - }, - "selected": false, - "capabilities": [] - } - ] -} -``` - -With a binding, `analysis_provider_binding` includes the selected identity, -selection source, and complete profile commitment. Every candidate reports -`supported`, `unsupported`, or `unknown` target support and whether it was -selected. Candidate capability descriptors preserve supported, unsupported, -and degraded truth independently. - -An open target also exposes `analysis_run`. Its run ID is allocated by the -session before client construction and propagated into selected Hopper or -Ghidra bridge handshake and process environment. Dynamic clients retain -provider-attributed lineage snapshots only after revalidating launcher -parent/command and every observed launcher or descendant run token. `not_observed` -means no dynamic provider has supplied a snapshot. Once one or more start, -`snapshots` preserves every provider observation; each remains explicitly -`unavailable` or `verified` and records its `observed_at` time. Retained -snapshots are not live inventories, and a point-in-time observation never proves -historical absence. - -Status exposes `analysis_provider_candidates` for configured deep providers and -`analysis_provider_binding` for the selected concrete provider and profile. -`capabilities` retains effective operation availability and exact provider -provenance, including auxiliary operation families. There are no synthetic -flat `provider` or `providers` aliases. Provider prompt completion uses the -actual selectable candidates. - -Selection failures extend the tagged `ProviderSelectionError` with a stable -reason: - -- `unknown_provider`; -- `provider_unavailable`; -- `target_unsupported`; -- `ambiguous`; -- `invalid_options`. - -The error includes the requested ID or `auto`, candidate IDs, rejection codes, -and actionable local diagnostics. `AnalysisCapabilityUnavailableError` remains -the error for an operation the selected provider cannot supply. -`ProviderAdapterError` and more specific provider errors remain failures of the -already selected provider. None authorizes fallback. - -A snapshot whose provider or profile differs from the selected binding returns -`EvidenceIntegrityError` with stable `profile_mismatch` details. It is an -integrity incompatibility after selection, not permission to select the -snapshot's provider. - -### 10. Preserve CLI and MCP parity - -- `open_binary.provider_id` and one-shot `--provider` use the same parser and - selection service. -- `provider_id: "auto"`, `--provider auto`, and - `REA_ANALYSIS_PROVIDER=auto` have identical auto semantics. -- Startup targets opened from environment configuration use the same service. -- `rea providers`, `rea capabilities`, and target-free `binary_session` use the - same candidate snapshot and reason codes. -- Guided prompt `provider_id` context is a preference to forward into the open - operation; it does not create a hidden routing channel. -- Tool names and normalized output contracts remain provider-neutral. REA does - not add `ghidra_decompile` or `hopper_decompile` tools. - -## Provider and snapshot representations - -| Behavior or data | Contract | -| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| No selector, one usable deep provider | `auto` selects the sole candidate | -| No usable deep provider | Automatic open may remain unbound for auxiliary operations; deep capabilities explain their unavailability | -| Several usable deep providers without a preference | Open fails with `ambiguous`; installation order never becomes policy | -| Hopper environment settings | Adapter configuration committed into the typed analysis profile, including effective loader arguments | -| `open_binary` output | Provider-neutral target identity only; no `loaderArgs` projection | -| `.hop` input | Analysis database accepted only by Hopper | -| Snapshots | Concrete provider/profile binding, required primitive and workflow entry arrays, and matching authenticated Evidence | -| Evidence without an observed profile | Explicit `analysis_profile: null`; ineligible for profile-dependent replay | -| Snapshot save receipt | `primitive_entries`, `workflow_entries`, and `evidence_records` counts without a duplicate `entries` alias | -| Provider failure after selection | Returned from that provider, without transparent retry through another engine | - -## Required behavior scenarios - -| Scenario | Result | -| ---------------------------------------------------------- | --------------------------------------------------------------------------- | -| Hopper is the only usable candidate, selector omitted | Hopper is bound by `auto-single-candidate` | -| Ghidra is the only usable candidate, selector omitted | Ghidra is bound by `auto-single-candidate` | -| Both are usable, selector omitted | Typed `ambiguous` error; neither provider starts | -| Environment selects Ghidra, request omits a selector | Ghidra is required and bound or the open fails with its rejection | -| Environment selects Ghidra, request selects Hopper | Request wins; Hopper is required | -| Environment selects Ghidra, request selects `auto` | Auto policy runs and is ambiguous when both are usable | -| Unknown concrete provider ID | Typed `unknown_provider`; no target transition | -| Selected provider rejects the target or options | Typed rejection from that candidate only | -| Selected provider times out after binding | Binding remains selected and unavailable; no fallback | -| Same target is reopened without a selector | Existing binding remains unchanged | -| Same bytes are opened with a different profile | Real provider switch and a separate snapshot partition | -| Snapshot provider or profile differs from the binding | Typed `EvidenceIntegrityError` with `profile_mismatch`; nothing is imported | -| Artifact-only target has no deep candidate | Target opens unbound; disjoint artifact capabilities remain usable | -| Environment prefers Ghidra for an artifact-only target | Deep selection is `not_applicable`; auxiliary operations remain usable | -| Concrete deep provider is requested for artifact-only data | Typed `target_unsupported`; the request is not silently ignored | - -## Consequences - -Positive consequences: - -- Hopper and Ghidra can coexist without ambiguous operation routes. -- Provider choice is reproducible, visible, and stable for a target. -- Installation of another provider cannot silently change analysis. -- Snapshot and Evidence identities become analysis-configuration aware. -- Provider adapters retain ownership of their option schemas and diagnostics. -- Auxiliary capabilities remain usable when no deep engine is installed. - -Costs and tradeoffs: - -- Multi-provider hosts must choose when more than one candidate is usable. -- Snapshots must be recaptured when their provider or profile binding changes. -- Providers must expose deterministic availability, support, version, and - profile resolution before they can be admitted. -- Status and error contracts gain additive structured metadata. -- Hopper needs an adapter-owned version/profile implementation before profile- - exact snapshot persistence is complete. - -## Rejected alternatives - -### Let `CompositeProvider` choose the first duplicate route - -Array order is not a product policy, becomes fragile during wiring changes, and -hides ambiguity from callers. - -### Race providers and keep the first healthy response - -Machine load would determine provenance and results. It also starts resources -the operator did not select and makes cancellation and cleanup harder. - -### Fall back after a provider error - -Mid-session fallback can combine incompatible engine state and evidence under -one apparent target. Explicit close or switch is required instead. - -### Add provider-prefixed tools - -Parallel Hopper and Ghidra tool families would leak adapters into the product -contract and prevent shared workflows from using capability metadata. - -### Store raw provider options in `BinaryTarget` - -That repeats the current Hopper coupling and makes every generic consumer learn -provider schemas. Only canonical profile commitments cross the adapter boundary. - -### Treat matching target bytes and provider ID as sufficient for snapshots - -Provider versions, analyzer defaults, loaders, languages, and compiler models -can change results without changing either value. - -### Silently upgrade snapshot v1 - -The missing engine version and analysis settings cannot be reconstructed from -Hopper loader arguments. A fabricated profile would turn unknown provenance -into false certainty. - -## Implementation progress - -The first six implementation stages are shipped: - -1. Provider-specific target state was replaced by generic profile and snapshot - v2 commitments while preserving Hopper execution behavior. -2. The registry, selectors, candidate status, binding lifecycle, and - overlapping-provider production seams were added. -3. Proven process-lifecycle primitives were extracted for shared use. -4. Ghidra availability, target/profile resolution, doctor checks, and a private - read-only headless session were admitted without declaring operations. -5. Program identity, procedures, strings, symbols, memory blocks, - address/name resolution, containing-procedure resolution, and search - were admitted with exact wire schemas and real debug/stripped ELF - conformance. -6. Function metadata, persistent decompilation, assembly, resolved - callers/callees, typed references, xrefs, CFG, and complete function dossiers - were admitted. A serial per-Program queue keeps API access ordered without a - fixed queue length or per-operation deadline. Real conformance covers - x86-64 and AArch64 ELF, PE, Mach-O, stripped symbols, targetless indirect - calls, cancellation, and cleanup. - -Future stages may deepen format and indirect-flow coverage, but must continue -to compare normalized semantics rather than provider-specific pseudocode or -assembly text. Linux and macOS now admit atomic function-name and entry-comment -edits in the ephemeral database, with readback, rollback, and cache invalidation. -Executable bytes remain unchanged. Windows P0 retains its read-only boundary; -GUI and other unimplemented mutations remain unavailable. diff --git a/docs/adr/0002-controlled-replay-authority-and-sandbox.md b/docs/adr/0002-controlled-replay-authority-and-sandbox.md deleted file mode 100644 index 6f5ae25de..000000000 --- a/docs/adr/0002-controlled-replay-authority-and-sandbox.md +++ /dev/null @@ -1,551 +0,0 @@ -# ADR-0002: Controlled JavaScript replay authority and sandbox policy - -- Status: Superseded; the controlled JavaScript replay tool was removed -- Date: 2026-07-16 -- Implementation status: The implementation was removed. The design below is - retained as historical context and does not describe a supported REA tool. - -> Historical design note: The tool, sandbox backend, and plan/execute workflow -> described here are no longer part of REA. For runtime behavior, run probes -> directly against the application and use the available browser, Electron, or -> process capture workflows. - -## Context - -REA can reconstruct JavaScript and Electron artifacts, observe an existing -browser or Electron page through passive CDP, capture an explicitly approved -process scenario, and correlate those observations without executing bundle -code in the REA server. The next research workflow needs to execute selected, -extracted JavaScript modules with controlled inputs and deterministic stubs so -that parsers, sanitizers, serializers, and similar pure logic can be compared -across versions. - -That workflow crosses a qualitatively different boundary. Source recovered -from an application is untrusted code. It can intentionally or accidentally -read files, contact services, spawn processes, exhaust resources, corrupt the -analysis process, forge protocol output, or interact with another same-user -process. A JavaScript realm or Node.js `vm` context is useful for constructing -an API surface, but it is not a security boundary. Node.js also documents its -permission model as protection against accidental access by trusted code, not -as containment for malicious code. - -Existing authorities cannot be widened to cover this behavior: - -- `browser_observe` and `electron_observe` authorize passive attachment to an - already-running, operator-owned target. They do not authorize evaluation, - navigation, input, or target lifecycle changes. -- `process_capture` authorizes one declared host process scenario and explicitly - states that it is not a sandbox. It cannot silently become permission to run - recovered code. -- static artifact reads authorize inspection of bytes, not execution of those - bytes. -- the Evidence authority `controlled-replay` already describes observations - from an approved process experiment. Reusing that epistemic authority is - correct, but reusing the process permission capability is not. - -The implementation following this ADR must fail closed on hosts where REA -cannot establish the promised operating-system boundary. It must not copy the -research `vm.runInContext` scripts into the production server and call that -isolation. - -## Decision drivers - -1. Passive observation must never imply authority to execute application code. -2. The exact code, inputs, stubs, runtime, sandbox policy, and limits approved - by the operator must be the ones executed. -3. Recovered code must not run in the MCP server, CLI adapter, or any provider - process. -4. A sandbox failure must make the capability unavailable, not select a weaker - execution mode. -5. The default policy must provide no host network and no writable host path. -6. Time, memory, process count, temporary storage, protocol, and output must be - bounded independently. -7. Results must distinguish an observed return, an observed exception or - termination, a derived comparison, and an unresolved application-level - claim. -8. A reproducer must commit enough provenance to detect every relevant change - without committing proprietary application source to the repository. -9. CLI and MCP must expose the same plan, approval, execution, cancellation, - failure, and Evidence semantics. - -## Terminology - -- **Passive observation**: bounded reads from an existing browser or Electron - target without evaluating code, driving input, navigating, or controlling - its lifecycle. -- **Controlled replay**: execution of operator-selected code in a declared, - isolated environment with committed inputs and limits. This is an Evidence - authority, not a claim that the real application behaved identically. -- **Extracted-module replay**: the only admitted JavaScript replay mode in v1. - REA evaluates a finite manifest of module bytes and explicit stubs without - launching the application. -- **Application interaction**: launching or driving the original application, - browser, renderer, or Electron main process. This is not extracted-module - replay and is not authorized by this ADR. -- **Replay plan**: the canonical, content-addressed description of one proposed - run before execution. -- **Replay worker**: the disposable Node.js process inside the OS sandbox. It - is never the REA server process. -- **Sandbox backend**: the OS mechanisms and adapter that establish namespaces, - resource controls, filesystem visibility, and owned cleanup. - -## Threat model - -### Protected assets - -The boundary protects: - -- the REA MCP/CLI process, its memory, credentials, sockets, and Evidence - ledger; -- user files outside the approved source reads and all host files from writes; -- other same-user processes and their control interfaces; -- host network interfaces, loopback services, Unix sockets, and external - services; -- process, memory, CPU, temporary-storage, output, and protocol capacity; -- the integrity of the replay plan, result, Evidence provenance, and exported - reproducer; and -- proprietary module bytes, which remain local and are never repository - fixtures. - -### Adversaries and failure sources - -REA treats all of the following as untrusted: - -- recovered module source, including transitive modules and source maps; -- caller-provided JavaScript stubs; -- structured test inputs and generated fuzz cases; -- returned values, exceptions, console data, and worker protocol messages; -- source paths, symbolic links, and files that can change between planning and - execution; and -- a worker that crashes, hangs, forks, allocates aggressively, or exits while - descendants remain alive. - -An operator-controlled sandbox executable, kernel, Node.js runtime, and REA -installation are trusted computing base. A hostile host administrator, kernel -or sandbox vulnerability, hardware side channel, and denial of service by an -already-compromised same-user process are out of scope. These exclusions do not -permit REA to omit the per-run resource controls in this decision. - -### Required mitigations - -The implementation must address: - -| Threat | Required control | -| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| Server-process compromise | Separate worker process inside the OS sandbox; no in-process fallback | -| Host file reads | Empty sandbox root; only a minimal read-only runtime closure; module bytes enter over a private bounded channel | -| Host file writes | No writable bind mounts; size-limited private tmpfs only | -| Network access | Separate network namespace with no host or external connectivity; no allowlist mode in v1 | -| Host process control | PID/user/IPC/UTS isolation, no inherited control sockets, new session, dropped capabilities | -| Kernel escape/inspection surface | Architecture-checked seccomp denial policy in addition to namespaces, capabilities, and cgroups | -| Fork, memory, or CPU exhaustion | Per-run cgroup v2 task, memory, swap, and CPU limits plus an outer wall-clock deadline | -| Output/protocol exhaustion | Independent byte/message/depth limits enforced by the parent before parsing or retaining output | -| Symlink and file-change races | Canonical authorization, descriptor-backed reads, digesting, staging, and exact plan revalidation | -| Undeclared dependencies | Closed module manifest; exact imports only; missing/dynamic imports fail rather than use host resolution | -| Nondeterministic globals | Versioned clock, PRNG, locale, timezone, platform, and API stubs; undeclared globals are unavailable | -| Orphan descendants | Owned PID namespace and cgroup kill followed by an observable empty-cgroup cleanup check | -| Forged result claims | Framed worker protocol, strict schemas, parent-computed commitments, and bounded stderr kept separate | -| Secret leakage | Empty environment, no credential inheritance, bounded local results, and existing genuine-secret redaction | - -## Decision - -### 1. Add a distinct `javascript_replay` permission capability - -JavaScript replay receives a new permission capability named -`javascript_replay`. It does not inherit, imply, or satisfy -`process_capture`, `browser_observe`, `electron_observe`, artifact-read, or -workspace permissions. Grants for any of those capabilities do not satisfy a -JavaScript replay request, and a JavaScript replay grant does not authorize -them. - -The administrator ceiling is disabled by default. Its eventual configuration -must commit: - -- canonical roots from which module and optional stub files may be read; -- the exact Node.js and sandbox-backend executables; -- filesystem mount authority needed only to construct the private sandbox; -- network mode `none`; and -- no inherited environment names. - -Configuration establishes only the maximum authority. Every execution also -requires an active permission grant and literal per-call approval bound to the -exact replay plan. Project, session, and administrator grants may satisfy the -permission-policy layer, but none replace that per-run approval. - -Reproducer export is a separate host write after the sandbox has stopped. This -ADR's root-scoped `evidence_write` authority was removed; current exports use -the path supplied by the caller, while replay still waits for complete sandbox -cleanup before writing. - -### 2. Admit extracted modules only - -The v1 mode executes a finite, closed manifest of JavaScript modules. The -manifest identifies one entry module and every admitted dependency by a stable -sandbox alias and SHA-256 digest. Imports resolve only to another manifest -entry or to an explicitly declared, versioned stub. Bare package lookup, -ambient `node_modules`, import maps from the host, network imports, native -addons, WASI, FFI, child processes, workers, inspector activation, and implicit -dynamic import are unavailable. - -Modules and stubs are read and hashed by the authorized parent, then copied as -bytes through a bounded private channel. Original host paths are not mounted -into the sandbox. The worker cannot reopen the operator's source path. - -Source maps may supply locations, but source-map source code is not executed -unless its bytes are separately present in the approved manifest. A source-map -name or Webpack module ordinal is never execution authority. - -REA does not launch, attach to, navigate, click, type into, or terminate the -user's application under this capability. A full application process remains -an independently approved Process Capture experiment; browser and Electron -targets remain passive. Any future mode that drives an application or permits -host/allowlisted network requires a new ADR and a distinct permission scope. - -### 3. Use a two-phase, content-bound approval flow - -One public replay surface supports a plan phase and an execute phase with the -same schema through CLI and MCP. - -The plan phase: - -1. validates all caller input and hard limits before file access; -2. obtains authority to read every selected module or stub path; -3. canonicalizes and opens each file without following an unapproved identity; -4. reads bounded bytes, computes digests, and closes the source descriptors; -5. resolves and probes the exact runtime and sandbox backend without running - application code; -6. normalizes stubs, inputs, generator settings, and limits; and -7. returns the complete proposed effects and a canonical `plan_digest`. - -The plan must disclose at least: - -- module aliases, canonical local paths, byte counts, and SHA-256 digests; -- input and stub identities, provenance, and digests; -- runtime and sandbox executable paths, versions, and executable digests; -- sandbox policy version and digest; -- network `none`, visible read-only runtime paths, and private writable tmpfs - size; -- time, CPU, memory, swap, task, temporary-storage, input, output, protocol, - case-count, and serialization limits; -- deterministic clock, PRNG seed/algorithm, locale, timezone, and platform - projection; and -- expected Evidence and cleanup behavior. - -Execution requires the exact `plan_digest`. REA -rebuilds the plan immediately before admission. Any changed file, runtime, -sandbox executable, policy, stub, input, limit, or environment commitment -returns `plan_stale` before application code starts. Approval is not transferable -to a different plan and cannot be represented by a bare Boolean alone. - -Interactive CLI may print the plan and ask for confirmation. Non-interactive -CLI and MCP must perform the same explicit plan/execute exchange; they may not -auto-approve because the caller requested JSON output or because permission -elicitation is supported. - -### 4. Require an OS sandbox; fail closed elsewhere - -The first production backend is Linux-only. It must combine: - -- an empty mount namespace rooted in private tmpfs; -- a new user namespace with all capabilities dropped and further nested user - namespaces disabled; -- new PID, network, IPC, UTS, and cgroup namespaces; -- a new terminal session and parent-death behavior; -- no host D-Bus, agent, browser, Docker, Wayland/X11, SSH, GPG, audio, device, - or application sockets; -- a minimal, read-only runtime closure rather than `/`, the user's home, - working directory, or host `/tmp`; -- a fresh `/proc` for the sandbox PID namespace and a minimal private `/dev`; -- a parent-generated, architecture-checked seccomp policy that denies at least - namespace or mount changes, `ptrace` and cross-process memory inspection, - BPF/perf access, kernel keyring and module control, reboot/swap controls, and - the `TIOCSTI` terminal injection path; -- cgroup v2 `memory.max`, `memory.swap.max=0`, `pids.max`, and bounded CPU - controls owned for the one run; and -- an outer REA supervisor that can kill the complete cgroup and verify it is - empty. - -The seccomp program is passed by descriptor, has a version and digest committed -to the replay plan, validates the syscall architecture before the syscall -number, and never permits `ptrace`-based mediation. Seccomp reduces exposed -kernel surface; it is not described as a complete sandbox by itself. - -The reference backend for the implementation PR is Bubblewrap for namespace, -mount, and seccomp construction plus a delegated cgroup v2 manager for resource -enforcement. REA must feature-probe the actual required operations; version -text alone is insufficient. A setuid Bubblewrap installation, a backend that -silently skips a requested namespace or filter, unavailable user namespaces, -missing cgroup delegation, or inability to prove cleanup makes the capability -unavailable. REA setup must not install or upgrade Bubblewrap, systemd, Node.js, -or kernel components. - -macOS, Windows, Linux hosts without every required feature, containers that -block the required namespaces, and alternative backends are unavailable in -v1. They must return precise diagnostics and remediation, not a process-only or -`vm`-only degraded mode. - -Node.js runs with its permission model enabled and without grants for network, -filesystem, child processes, workers, native addons, WASI, FFI, or inspector. -That layer is defense in depth. It is never cited as the OS security boundary, -because Node.js explicitly does not promise containment of malicious code. - -### 5. Make the worker disposable and deterministic by construction - -Each approved run receives a new sandbox, runtime root, worker process, module -loader, and deterministic state. No module cache, realm, timer, file, global, -or child survives into another run. Within a multi-case run, every case gets a -fresh realm and fresh module instances; case order and generator state are -committed. - -The worker exposes a small versioned set of language primitives and explicitly -selected stubs. It does not expose `process`, `require`, host `console`, timers, -`fetch`, sockets, filesystem APIs, `Buffer`, worker APIs, native bindings, or -ambient environment variables. Date/time, randomness, locale, timezone, and -platform values come only from committed deterministic providers. An -unsupported global or import produces an observed exception; REA does not -substitute a convenient host implementation. - -Caller-provided stubs are executable untrusted code and receive the same -sandbox treatment as recovered modules. Built-in stubs have stable IDs, -versions, canonical source digests, and documented semantics. No undeclared -fallback stub is allowed. - -Inputs are bounded canonical JSON. Results are projected without invoking -getters, proxies, `toJSON`, or arbitrary coercion: only admitted primitives, -arrays, and plain data properties are serialized. Cycles, accessors, functions, -symbols, unsupported prototypes, excessive depth, excessive nodes, and -oversized values become explicit serialization outcomes. Worker stdout is the -framed protocol only; bounded diagnostic stderr and bounded, opt-in console -observations remain separate. - -### 6. Enforce independent resource ceilings - -Every limit has a conservative product default. The v1 plan and result commit: - -- an outer wall-clock deadline for the complete disposable run; -- cgroup memory, swap, task, and CPU ceilings; -- Node/V8 heap ceiling as defense in depth; -- private tmpfs bytes; -- serialized worker-protocol bytes, aggregate module bytes, and case-input - bytes; preset-generated cases also have a fixed preflight count ceiling; -- stdout, stderr, exception, stack, and aggregate retained-output bytes; and -- structured-result depth and node count. - -The parent enforces protocol and output limits while bytes arrive, before JSON -parse or Evidence retention. The worker cannot request wider limits. A limit -hit terminates the complete run cgroup and is an observed termination, not a -partial successful return. - -### 7. Preserve exact provenance and the right Evidence authority - -A run that reaches worker admission produces Evidence with: - -- provider `rea-javascript-replay` and a concrete implementation version; -- operation `run_controlled_replay`; -- authority `controlled-replay`; -- confidence `observed` for the exact returned value, thrown exception, - sandbox denial, limit termination, signal, exit, or crash that REA directly - observed; -- environment isolation `container`, the host platform/architecture, runtime - identity, sandbox-backend identity, and sandbox-policy digest; -- the replay plan digest, module and stub digests, canonical input or generated - case digests, deterministic providers, and every effective limit; -- bounded raw input, output, and exception data when retained, plus their - canonical digests and truncation state; -- start/admission/termination/cleanup states; and -- explicit limitations for incomplete output, nondeterminism not checked, - sandbox diagnostics, or cleanup that could not be proven. - -The host module path remains an actionable local diagnostic and Evidence -subject location, while the worker sees only a stable alias. Module source is -not embedded in ordinary Evidence. A separately approved reproducer may copy -module/stub bytes or may retain path-plus-digest references; its manifest says -which mode was used. Repository tests use source-owned fixtures, and real-app -verification stores only digests and expected structural facts. - -Derived differential results use confidence `derived` and link every source -run Evidence ID. A repeat with the same commitment can establish -`repeat-confirmed` for those runs; a single deterministic plan is only -`committed-not-confirmed`. Neither state proves behavior in the original -application. - -When replay observations are added to the JavaScript Application Graph, their -graph-fact authority is `controlled-replay`. A claim that the real renderer, -preload, main process, or remote service behaves the same remains inferred or -unknown until compatible runtime authority exists. Static inference, passive -CDP observation, controlled replay, and real application interaction are never -promoted into one another. - -### 8. Treat post-admission failures as observations - -Pre-admission failures return a typed error and create no claim that module code -ran. Once the worker is admitted, REA retains a bounded execution record even -when the requested function does not return normally. - -| Condition | Caller result and Evidence semantics | -| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | -| Disabled capability or missing grant | `permission_required`/`capability_unavailable`; no worker admission and no replay observation | -| Sandbox/runtime probe failure | `capability_unavailable` with exact failed feature; no module execution | -| Plan digest mismatch or changed source | `plan_stale`; no module execution | -| Sandbox setup fails before worker admission | `execution_failure`; no controlled-replay claim about the module | -| Module returns admitted data | Observed return value with complete or explicitly limited coverage | -| Module throws or result serialization rejects | Successful replay observation with outcome `exception` or `serialization_error`; application claim unknown | -| Node permission or sandbox denies an operation | Observed denial/termination when attributable; no claim that all attempted side effects were enumerated | -| Timeout, memory, CPU, task, tmpfs, or output hit | Observed limit termination; requested functional result unknown | -| Signal, runtime crash, or malformed protocol | Observed termination plus bounded diagnostics; functional result unknown | -| Caller cancellation after admission | Kill full cgroup, record cancellation/cleanup if possible, and project the public cancellation contract | -| Cleanup proves an empty cgroup and removed root | `cleanup: complete` | -| Cleanup cannot prove emptiness or removal | `cleanup_incomplete`, name every residual resource, and do not report success | - -An exception is data, not an adapter failure. A sandbox setup error is not -evidence that the module crashed. A timeout is not evidence that the function -would never return. An output limit is not evidence that the truncated prefix -equals the full result. These distinctions are part of the public contract. - -Cancellation and cleanup must be idempotent. REA first stops admission and -input, kills the owned cgroup, waits for an empty-cgroup observation, removes -the private runtime root, closes protocol descriptors, and releases timers. -Failure at one cleanup step does not skip the remaining steps. - -### 9. Keep replay records reproducible without overstating determinism - -The canonical replay manifest commits: - -```text -plan structure and policy identity -REA/provider/runtime/sandbox executable identities and digests -module aliases, dependency graph, bytes digests, and source references -stub IDs, versions, source digests, and caller-provided stub digests -canonical inputs or generator algorithm, seed, case order, and case digests -clock, PRNG, timezone, locale, platform, and exposed-global commitments -all resource and serialization limits -network and filesystem projections -expected entry export and invocation convention -``` - -The result manifest adds canonical output/exception/termination digests, -coverage, dropped-data counts, cleanup state, and source Evidence links. -Canonical digests are computed by the trusted parent; worker-provided digests -are ignored. - -Reproduction requires exact manifest compatibility. A runtime, sandbox policy, -built-in stub, module byte, generated case, limit, architecture, or platform -change is a different experiment. Cross-environment comparison may still be a -derived investigation, but it is never an exact replay. - -### 10. Expose availability and policy truth before execution - -`rea doctor`, capability inventory, and the planning response must report the -JavaScript replay capability without executing application code. Diagnostics -name the exact missing executable, unsupported host, failed namespace feature, -cgroup delegation failure, setuid rejection, runtime mismatch, or cleanup-probe -failure. Genuine secrets remain redacted; local executable paths, versions, -digests, and kernel feature failures remain visible. - -The capability must be absent from executable tool routing until implemented. -Accepting this ADR does not increase the current tool count and does not add a -hidden experimental flag. - -## Required implementation and verification gate - -The implementation PR cannot merge until all of the following are true: - -1. `javascript_replay` exists in configuration, permission policy, project - grants, policy explanation, CLI, MCP, docs, and capability inventory with - fail-closed defaults. -2. Plan and execute phases have schema-identical CLI/MCP behavior and an exact - plan-digest stale check. -3. No replay-disabled static, browser, Electron, session, setup, doctor, or - application workflow can reach module execution. -4. The worker never imports into the REA server process and no adapter offers a - `vm`-only fallback. -5. The Linux backend feature-probes namespaces, seccomp installation and - denial, delegated cgroup v2 limits, and the exact admitted architecture. - Every plan content-addresses the worker, seccomp filter, Node executable, - ELF loader, shared-library closure, and sandbox executables. -6. Source-owned fixtures cover parser, sanitizer, clipboard, exception, - ambient side-effect attempts, memory pressure, and busy loops. The worker - exposes no filesystem, environment, network, process, worker, native-addon, - timer, inspector, or ambient package-resolution API. -7. Tests and the real verifier prove bounded protocol/diagnostics, timeout and - OOM cgroup termination, and observed cgroup cleanup. -8. Evidence tests cover observed return/exception/termination, derived - comparison with source Evidence links, stale admission, cancellation - projection, and explicit limitations on application-level claims. -9. Package verification exercises the target-free public contract. The - dedicated real-Linux workflow exercises the sandbox backend; environments - without delegated user namespaces or cgroups report truthful unavailability - rather than selecting a weaker backend. -10. A real operator-local Notion-like parser or sanitizer benchmark can run - without committing its source, and exports only approved local reproducer - material. - -## Rejected alternatives - -### Reuse `browser_observe`, `electron_observe`, or `process_capture` - -Rejected because those grants authorize different effects. Reuse would turn a -passive or unsandboxed process permission into recovered-code execution. - -### Execute in the MCP server with `vm.runInContext` - -Rejected because a VM context is not a security boundary and a crash, resource -attack, or escape would compromise the long-lived session and its credentials. - -### Use only the Node.js permission model - -Rejected because Node.js documents it as a seat belt for trusted code and -explicitly does not guarantee containment of malicious code. It remains a -defense-in-depth layer inside the OS sandbox. - -### Ship a process-only fallback on unsupported hosts - -Rejected because it changes the security claim while preserving the same tool -name. Unsupported hosts return unavailable. - -### Permit network allowlists in v1 - -Rejected because DNS, redirects, proxies, credentials, service identity, and -response nondeterminism would substantially expand the threat and Evidence -model. The v1 namespace has no host or external network. - -### Mount the approved project root read-only - -Rejected because one approved module does not imply authority to disclose -every file in its project. The parent stages only exact, digested bytes. - -### Treat exceptions, crashes, or limit hits as ordinary tool errors only - -Rejected because that discards the principal behavioral observation and makes -negative results impossible to reproduce. Post-admission termination is -retained with explicit functional uncertainty. - -## Consequences - -- JavaScript replay is Linux-only at first and may be unavailable on containers - or distributions that disable user namespaces or cgroup delegation. -- The implementation requires more host probing and lifecycle code than a - simple Node worker, but the public security claim remains stable. -- Plans require two calls in non-interactive environments and become stale when - any committed input changes. -- Network-dependent modules and full application interactions are excluded; - their absence is explicit rather than emulated implicitly. -- Results are reproducible for the committed isolated experiment, not proof of - production behavior. -- Adding another sandbox backend, network mode, or application-interaction mode - requires a separate reviewed decision and conformance suite. - -## References - -- [Node.js permissions](https://nodejs.org/api/permissions.html) documents that - the permission model does not protect against malicious code and describes - its known filesystem and cross-process limitations. -- [Bubblewrap README](https://github.com/containers/bubblewrap/blob/main/README.md) - describes its namespace construction and makes clear that the caller's - arguments, not Bubblewrap alone, define the sandbox security model. -- [Linux seccomp filter documentation](https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html) - explains that syscall filtering reduces kernel surface but is not a complete - sandbox by itself. -- [ADR-0001](0001-provider-selection-and-analysis-profiles.md) establishes the - existing rule that provider selection, Evidence provenance, and capability - unavailability remain explicit and never silently fall back. diff --git a/docs/adr/0003-managed-code-evidence-and-provider-boundary.md b/docs/adr/0003-managed-code-evidence-and-provider-boundary.md deleted file mode 100644 index bd3895fb4..000000000 --- a/docs/adr/0003-managed-code-evidence-and-provider-boundary.md +++ /dev/null @@ -1,452 +0,0 @@ -# ADR-0003: Managed-code evidence and provider boundary - -> Historical design record: The non-executing runtime-correlation planning -> tool described in earlier revisions was removed. This ADR's current -> implementation status below covers only the static managed tools that ship. - -- Status: Superseded for runtime planning; static evidence boundary remains in force -- Date: 2026-07-16 -- Implementation status: Read-only PE/CLI triage and exact identity are shipped - through `inspect_managed_artifact` / `rea inspect-managed-artifact`. Bounded - metadata, signatures, method bodies, raw CIL hashes, limited - decoded-instruction-tuple v1 hashes, exception regions, call edges, and - field-access anchors are shipped through `inspect_managed_members`; `rea - inspect-managed-members` provides CLI parity. Static member comparison and build-local - token remapping are shipped through `compare_managed_members` / - `rea compare-managed-members`. Declaration-only managed/native boundary - inventory for ModuleRef, ImplMap/PInvoke, ReadyToRun indicators, and non-IL - method flags is shipped through `inspect_managed_native_boundaries` / - `rea inspect-managed-native-boundaries`. Managed/native export or function - Evidence matching is shipped through `verify_managed_native_boundaries` / - `rea verify-managed-native-boundaries`; it verifies only supplied P/Invoke - export/function observations and does not map managed tokens to native - addresses. Decompiler reconstruction import is - shipped through `import_managed_reconstruction` / - `rea import-managed-reconstruction`; it records user-supplied C#/IL/pseudocode - as analyst inference only after exact static member locks match. Managed - inspection does not execute assemblies or observe CLR internals. Managed static graph - projection is shipped through - `project_managed_application_graph` / - `rea project-managed-application-graph`; it projects authenticated managed - Evidence into the application graph without changing managed tokens into - native addresses. Native-body bridge mapping and an actual runtime executor - remain future contracts. - -## Context - -Professional C# reverse engineering is not one decompiler operation. A file -described as “.NET” can be ordinary Common Intermediate Language (CIL), -ReadyToRun code containing both CIL and native implementations, a single-file -deployment, C++/CLI mixed mode, Unity Mono, Unity IL2CPP, or NativeAOT. Those -forms have different sources of truth and different native-analysis needs. -Choosing a decompiler before classifying the artifact can therefore produce a -plausible but false model. - -The durable static facts in an ordinary managed PE are its PE/CLI headers, -metadata tables, signatures, method bodies, exception regions, and CIL. A C# -decompiler reconstructs source-like control flow and language constructs from -those facts. That reconstruction is valuable, but it is not the original -source and cannot replace the underlying metadata and CIL evidence. Obfuscation -makes names especially weak while tokens remain coordinates in only one build. - -REA already separates one selected deep native provider from disjoint auxiliary -providers under [ADR-0001](0001-provider-selection-and-analysis-profiles.md). -It also separates static evidence, passive observation, process capture, and -interactive observation authorities. Managed analysis must fit those boundaries -without requiring a CLR to inspect an artifact, loading target code into the -REA process, or treating a managed token as a native address. - -The design is informed by exact-build, reflection-free metadata extraction, -hash-locked method manifests, independent behavior models, and managed/native -boundary analysis performed against a local C# application. The application, -its decompiler output, and its runtime observations are research inputs only; -they are not distributable REA fixtures. - -## Decision drivers - -1. Classify the deployment before selecting an analysis route. -2. Make metadata and CIL independently inspectable without a CLR or target - execution. -3. Preserve exact-build provenance while enabling structural comparison across - builds whose MVIDs, tokens, names, and layout differ. -4. Compose managed and native analysis without introducing another ambiguous - deep-provider candidate. -5. Keep decompiled C# useful but epistemically subordinate to canonical bytes. -6. Analyze Linux, macOS, and Windows managed artifacts through the same local - CLI/MCP contracts on REA's supported hosts. -7. Keep setup additive and prevent managed analysis from installing .NET, - ILSpy, an SDK, or another unrelated toolchain. -8. Prove semantics with source-built conformance artifacts and compact, - operator-local real-application checks. - -## Terminology - -- **Managed artifact**: a PE, bundle component, or related metadata artifact - that carries a CLI header, CLI metadata, CIL, or another managed-runtime - commitment. -- **Classification vector**: independently observed container, runtime family, - implementation form, and architecture. It is not one guessed label. -- **Canonical static observation**: a bounded value decoded directly from the - target bytes under a versioned parser contract. -- **Reconstruction**: source-like output, including decompiled C#, derived from - canonical observations. -- **Structural inference**: a relationship or cross-version match derived from - signatures, APIs, constants, control/data-flow shape, or other observations. -- **Validation**: an independently checked proposition, for example a - source-built oracle assertion or a behavior-model corpus result. -- **Runtime observation**: a separately authorized fact obtained by attaching, - loading, debugging, instrumenting, or otherwise executing code. - -## Decision - -### 1. Classify before analyzing - -Managed triage returns a classification vector and the observations supporting -each dimension. Absence of a marker produces `unknown` or `not_applicable`, not -an invented runtime family. - -| Dimension | Initial values | -| ------------------- | ------------------------------------------------------------------------------------------------------------ | -| Container | PE file, single-file bundle, bundle component, Unity metadata pair, native image, malformed, unknown | -| Runtime family | .NET Framework, modern .NET, Unity Mono, Unity IL2CPP, NativeAOT, mixed CLR/native, unknown | -| Implementation form | CIL, CIL plus ReadyToRun, native only, C++/CLI mixed, metadata only, unsupported, unknown | -| Architecture | PE machine plus CLI flags; component-specific architecture for bundles; conflicting or unknown when required | - -Target-framework attributes, assembly references, metadata stream versions, -bundle manifests, ReadyToRun directories, and native headers are observations. -They may support a runtime-family inference, but no single string is treated as -authoritative when the other bytes conflict. - -Classification selects these routes: - -| Observed form | Managed route | Native route and limitation | -| --------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | -| Ordinary Framework or modern CIL | Full metadata, signatures, method bodies, and CIL | Optional only for declared interop boundaries | -| Obfuscated CIL | Same canonical route; names receive no special trust | Optional for declared interop boundaries | -| Unity Mono assembly | Same canonical route with Unity context retained | Optional for engine/native boundaries | -| ReadyToRun | Metadata/CIL where present; implementation availability is per method | Selected Hopper/Ghidra analyzes native sections; CIL absence is reported per method | -| C++/CLI mixed mode | Metadata/CIL for managed members and explicit mixed-mode boundary observations | Selected Hopper/Ghidra analyzes native bodies; REA never converts tokens directly to native addresses | -| Single-file deployment | Inventory the bundle, then analyze each authenticated managed component | Selected Hopper/Ghidra analyzes the host/native components; unsupported compression remains explicit | -| Unity IL2CPP | Pair and authenticate available Unity metadata; do not claim canonical CIL | Selected Hopper/Ghidra analyzes the generated native binary; semantic recovery is degraded until supported | -| NativeAOT | Report any independently present managed metadata, otherwise no CIL claim | Treat as a native target with NativeAOT provenance; managed source reconstruction is unavailable | -| Malformed or unsupported artifact | Return bounded partial observations and typed unavailable/unknown scopes | Do not silently retry by loading or executing the file | - -Classification is byte-driven and bounded. File extensions, product names, -process names, and an operator's description are hints only. - -### 2. Implement managed static analysis as a disjoint auxiliary provider - -The initial producer is a REA-owned auxiliary provider with ID -`rea-dotnet-static`. It owns a disjoint managed-artifact operation family. It is -not registered as a Hopper/Ghidra deep-provider candidate because it does not -compete for the same operation names and must be able to coexist with the one -selected native provider. - -```text - one opened artifact/session - | - SessionProviderRouter - / \ - rea-dotnet-static auxiliary selected deep binding - PE/CLI metadata and CIL Hopper or Ghidra - \ / - explicit managed/native links - | - Evidence and workflows -``` - -An ordinary managed artifact can therefore remain unbound to a deep native -provider while managed operations work. ReadyToRun, C++/CLI, IL2CPP, NativeAOT, -and interop workflows may additionally require a caller-selected native -binding. Native-provider failure never causes managed evidence to be relabeled, -and managed-parser failure never causes an implicit native fallback. - -Provider mechanics live under a provider directory such as `src/dotnet/`. -Provider-neutral identities, evidence states, and bounded values may live in -the domain/contracts layers. Application code composes results but does not -parse PE headers, metadata tables, signatures, CIL, ReadyToRun headers, or -provider-specific output. - -### 3. Make the production static path byte-only and execution-free - -`rea-dotnet-static` reads approved local bytes and implements the required -PE/CLI metadata and CIL subset in TypeScript. It does not call any reflection -API and does not require the .NET runtime. In particular, static inspection -must never: - -- call `Assembly.Load`, `Assembly.LoadFrom`, `ReflectionOnlyLoad`, or an - equivalent runtime loader; -- resolve target dependencies by executing target-controlled resolver code; -- run module initializers, constructors, entry points, build tasks, plugins, or - generated helpers; -- start the target, attach to a process, contact a service, or inherit target - configuration and credentials; or -- interpret a decompiler, CLR, or native-provider diagnostic as an observation - from the artifact bytes. - -The parser uses checked offsets and additions, explicit endianness, bounded -table/heap/body counts, cycle-safe traversal, and typed partial results. A bad -row, signature, body, resource, or stream does not authorize an unbounded retry -or a CLR load. Complete-coverage claims require every applicable bounded region -to have been admitted; otherwise coverage is partial, unknown, or unavailable -with exact offsets and reasons. - -The caller selects the local input path directly. Local artifact -paths, digests, MVIDs, tokens, malformed offsets, and analysis metadata are -actionable diagnostics and are not secrets. Credentials, authorization data, -and genuine secrets remain redacted. - -### 4. Bind every finding to exact artifact and producer identity - -Every managed result carries a commitment with at least: - -```text -artifact: canonical path + byte length + SHA-256 -component: container identity + component path/name + component SHA-256, when applicable -classification: container + runtime family + implementation form + architecture -assembly/module: simple name + version + culture + public-key identity + module name + MVID -producer: provider ID + exact version + analysis-affecting parameters + profile digest -``` - -An assembly-qualified name does not replace the artifact digest or MVID. -Neither an MVID nor an Authenticode signature proves who authored the behavior. -Bundle components retain both their container and component commitments so that -bytes extracted from another host cannot be silently substituted. - -Method observations add: - -```text -declaring type + normalized CLI signature -build-local metadata token -RVA/file extent when present -raw CIL byte length + SHA-256 when the body is admitted -decoded-instruction-tuple SHA-256 when CIL is valid -separate max-stack, locals-token, and exception-region observations -``` - -The shipped `il_sha256` commits only the raw CIL byte stream identified by the -method header's `il_size`. It does not commit the method header, local-signature -blob, alignment padding, or extra sections such as exception clauses. Those -facts remain separate observations and the enclosing artifact SHA-256 binds -them to the exact file. A digest over the complete method body is not shipped. - -The caller-visible field remains named `normalized_il_sha256`, but its shipped -v1 meaning is deliberately narrower than a canonical semantic CIL identity. -For a completely decoded method, REA serializes the instruction-order array of -`[opcode, operand_kind, operand]` tuples with JavaScript `JSON.stringify`, -encodes that text as UTF-8, and reports its lowercase SHA-256. The tuple -projection is defined here; the member result carries only the described -normalized digest. - -Operands retain the current decoder projection: metadata and user-string -operands are build-local lowercase hexadecimal tokens, scalar branch operands -are decimal target CIL byte offsets, and `switch` retains only its decimal case -count. Constants and variable indexes are decimal strings; an operand-free -instruction uses kind `none` and value `null`. Opcode names preserve distinct -short forms and prefix instructions, but instruction offsets, branch target -instruction identity, switch targets, resolved token identities, method -headers, locals, and exception regions are not part of this digest. A partial -or malformed decode has no `normalized_il_sha256`. - -Consequently v1 is a deterministic decoded-tuple fingerprint, not proof of -semantic equivalence. In particular, methods with the same opcodes and switch -case counts can share it despite different switch targets, and token movement -can change it without a semantic change. Cross-build comparison may use it as -one unique-only structural tier while retaining artifact/MVID commitments and -ambiguity; it must not describe the digest itself as token-remapped canonical -CIL. Canonical operand resolution, complete control-flow operands, -exception/local commitments, and an explicit algorithm version require a new -normalized-CIL schema. - -Metadata tokens are reported because they are precise coordinates inside one -module. Cross-version identity never consists of a token alone. Matching tries -exact CIL/signature identity, then an exact declared-type/name/signature tuple, -then structural shape; a name by itself never selects a pair. Partial or -malformed bodies leave body facets unknown after a signature tuple pairs the -methods. Matches cite both build commitments, both local tokens, and all -competing candidates. V1 cannot cite a separate matching-algorithm version -because none is exposed. - -### 5. Separate five evidence layers - -Managed workflows retain these layers independently: - -| Layer | Examples | Permitted claim | -| ---------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------- | -| Static observation | Metadata row, signature, CIL opcode, literal, exception region | “These bounded bytes decode to this value.” | -| Reconstruction | Decompiled C#, async/iterator source shape, expression simplification | “This is one source-like representation of cited observations.” | -| Structural inference | Likely caller, field flow, behavior slice, cross-build method match | “These cited structures support this relationship.” | -| Independent validation | Synthetic oracle, corpus result, second parser agreement | “This declared proposition passed the named independent check.” | -| Runtime observation | Exact-build attach/load/instrumentation event | “This separately authorized experiment observed this event.” | - -Each layer has its own producer, authority, state, confidence, coverage, and -limitations. A readable C# method is never emitted as original source or exact -semantic proof. A validator does not upgrade unrelated claims. Runtime -agreement does not retroactively turn a static inference into an observation. - -Negative results are scope-qualified. For example, “no declared P/Invoke rows -were found in the admitted metadata tables” does not prove the application has -no native, dynamically resolved, generated, server-side, or protected path. - -### 6. Admit ILSpy only as an optional reconstruction and conformance tool - -REA's canonical static operations do not depend on ILSpy, a .NET SDK/runtime, -dnlib, or Mono.Cecil. The following review was current on the decision date: - -| Tool | Reviewed coordinate | License | Runtime/host observation | Decision | -| ---------------------------- | ------------------- | ------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -| `System.Reflection.Metadata` | 10.0.10 | MIT | Library targets .NET Framework 4.6.2, .NET 8/9/10, and .NET Standard 2.0 | Pinned independent metadata oracle for conformance; not shipped or invoked by production parsing | -| `ICSharpCode.Decompiler` | 10.1.1.8388 | MIT | Library targets .NET Standard 2.0; output is reconstruction | Pinned reconstruction/differential oracle candidate | -| `ilspycmd` | 9.1.0.7988 | MIT | Cross-platform .NET 8 tool; newer 10.1.1.8388 requires .NET 10 | Initial optional BYO reconstruction coordinate because it matches the source research baseline | -| dnlib | 4.5.0 | MIT | Cross-platform library; also exposes assembly-writing APIs | Differential test candidate only; its writable model is outside the production trust boundary | -| Mono.Cecil | 0.11.6 | MIT | Cross-platform .NET Framework/.NET Standard library with read/write support | Differential test candidate only; not a production dependency | - -Coordinates and package hashes used by real verification are checked into a -source-owned lock manifest when that verifier is implemented. “Latest” is -never a reproducibility coordinate. A version change requires conformance and -an explicit profile/version change. - -Artifact platform and REA host support are separate. The byte-only parser must -inspect PE/CLI artifacts produced for Windows on a supported Linux or macOS REA -host; that is not a claim that REA itself currently runs on Windows. Managed -library/tool candidates above are cross-platform at their reviewed targets, but -native composition remains limited by the selected Hopper/Ghidra host and -format support. Real verification runs the canonical path on Linux and macOS -and may run pinned oracle checks on Windows without turning that development -check into a public Windows-host claim. - -If a caller-visible C# reconstruction operation is admitted, it is a distinct -optional capability. It accepts only an exact supported BYO `ilspycmd`, records -the tool and decompiler version, runs in an owned bounded process without -loading target code into REA, and links output to the canonical method -observation. Setup and installers do not download or install ILSpy, .NET, an -SDK, or a runtime. Doctor may inspect an explicitly configured executable and -report exact actionable incompatibility. Missing reconstruction never removes -canonical metadata/CIL capabilities. - -This decision does not make a decompiler process a security sandbox. The -initial public path can defer C# reconstruction while canonical contracts and -process isolation are proven. - -### 7. Use source-built conformance and operator-local real targets - -The repository stores source, build descriptions, expected semantic facts, -and tool lock manifests, but not compiled managed binaries. An isolated build -step creates fixtures outside source directories and records their SHA-256 and -MVID before verification. At minimum, the corpus covers: - -- Framework-compatible and modern .NET metadata; -- AnyCPU, x86, and x64 PE/CLI flags; -- generics, nested types, overloaded signatures, properties, events, resources, - attributes, and constants; -- exceptions, filters, prefixes, switch branches, P/Invoke, async and iterator - state machines; -- obfuscated and Unicode names without assigning semantics from names; -- malformed headers, tables, heaps, signatures, bodies, and exception regions; - and -- two semantically related builds with different MVIDs, tokens, layout, and - selected names. - -Expected facts are checked directly and against pinned -`System.Reflection.Metadata`; ILSpy, dnlib, or Mono.Cecil may add differential -coverage but do not vote by majority. Disagreement is a failing or explicitly -unsupported case, not silently normalized output. - -The real-application benchmark is an operator-local, opt-in osu! check derived -from the research workflow. It accepts an explicit path plus a compact -expectation manifest; verifies target SHA-256, MVID, architecture, and expected -assembly identity before analysis; and emits only bounded identities, tokens, -signatures, IL lengths/hashes, match states, and assertion results. It does not -emit full IL, decompiled source, runtime logs, user data, credentials, or -service/account material. No proprietary binary, hash-locked application -manifest, or derived dump is committed to REA. - -### 8. Keep runtime behavior separate from static managed analysis - -No managed runtime planning or execution tool ships. Managed inspection does -not execute assemblies or establish which methods ran. Where supported, direct -process capture can record target-level inputs and outputs, but it does not -prove CLR method execution or resolution. Internal managed behavior remains -unknown until independently observed with suitable runtime evidence. - -## Public contract consequences - -- Managed static operations will have CLI and MCP parity and produce the same - Evidence commitments. -- Adding managed operations changes the caller-visible tool inventory and - generated product catalog only in the implementation PR that admits them. -- Partial parsing includes admitted/dropped counts, exact limitations, and - coverage; it never returns a partial list labeled complete. -- Managed addresses distinguish file offsets, RVAs, native virtual addresses, - metadata tokens, and CIL offsets. They are not interchangeable. -- Cache compatibility is exact on artifact/component commitment, member-result - fields, parser profile, and producer version. For shipped v1, - `normalized_il_sha256` has no independent algorithm-version field. -- Provider-neutral workflows may compose canonical managed findings with the - one native binding, but every source operation retains its actual producer. - -## Alternatives rejected - -### Make ILSpy the only managed provider - -This would make canonical metadata/IL inventory depend on a separately -installed CLR and conflate source reconstruction with byte observations. It -would also make tool-version drift part of ordinary inventory. ILSpy remains a -valuable optional reconstruction and conformance tool instead. - -### Use `Assembly.Load` or reflection-only loading - -Both delegate parsing and dependency behavior to a CLR and make static support -runtime-dependent. Ordinary loading can execute target code; reflection-only -loading still establishes a CLR load boundary and is unavailable across modern -runtimes in a uniform way. Neither is required to decode ECMA-335 bytes. - -### Register the managed analyzer as another deep candidate - -That would force callers to choose managed analysis instead of Hopper/Ghidra -for ReadyToRun and mixed-mode artifacts even though both are needed. Disjoint -auxiliary composition represents the real ownership boundary. - -### Treat tokens, names, or decompiler output as durable identity - -Tokens and obfuscated names change across builds, while decompiler output -changes across tools and versions. They remain useful build-local coordinates -or reconstruction labels but are insufficient for exact or structural -cross-version identity. - -### Package a .NET runtime or mutable managed library in REA - -This would expand installer effects, package size, patching obligations, and -the target-parsing attack surface. The initial byte parser keeps canonical -support within REA's existing Node runtime; external managed tools remain BYO -or development-only oracles. - -## Rollout gates - -1. Add read-only triage and identity with malformed-input bounds. Shipped. -2. Add metadata, signatures, method bodies, deterministic decoded-CIL tuple - fingerprints, and exact artifact Evidence. Shipped with the v1 limitations - above; full normalized-CIL semantics remain planned. -3. Add obfuscation-resistant slices and cross-build match states. Shipped. -4. Compose explicit managed/native boundaries with Hopper/Ghidra. Declaration - inventory and native export/function Evidence matching shipped; native-body - bridge mapping remains planned. -5. Add source-built, pinned real-tool, package, CLI, and MCP conformance. - Source-owned conformance is shipped; pinned external real-tool checks remain - planned. -6. Project authenticated managed static Evidence into the application graph. - Shipped. - -Every gate must keep unsupported ReadyToRun, NativeAOT, IL2CPP, mixed-mode, or -bundle cases explicit rather than broadening claims to make a fixture pass. - -## References - -- [ECMA-335: Common Language Infrastructure](https://ecma-international.org/publications-and-standards/standards/ecma-335/) -- [.NET ReadyToRun deployment overview](https://learn.microsoft.com/en-us/dotnet/core/deploying/ready-to-run) -- [.NET Native AOT deployment overview](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/) -- [.NET single-file deployment overview](https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview) -- [`System.Reflection.Metadata` package](https://www.nuget.org/packages/System.Reflection.Metadata/10.0.10) -- [ILSpy repository and releases](https://github.com/icsharpcode/ILSpy) -- [dnlib repository](https://github.com/0xd4d/dnlib) -- [Mono.Cecil repository](https://github.com/jbevain/cecil) diff --git a/docs/adr/README.md b/docs/adr/README.md deleted file mode 100644 index 7130daa78..000000000 --- a/docs/adr/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Architecture decision records - -Accepted decisions describe the architecture that implementation PRs must -follow. Acceptance does not by itself mean the behavior is shipped; each record -states its implementation status separately. - -| ADR | Status | Implementation | -| ------------------------------------------------------------------------------------------------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| [0001: Provider selection and analysis profiles](0001-provider-selection-and-analysis-profiles.md) | Accepted | Provider selection and 25 read-only Ghidra operations on Linux/macOS and experimental Windows x64 P0; Linux/macOS session annotations | -| [0002: Controlled JavaScript replay authority and sandbox policy](0002-controlled-replay-authority-and-sandbox.md) | Superseded | Historical design; the controlled JavaScript replay tool was removed | -| [0003: Managed-code evidence and provider boundary](0003-managed-code-evidence-and-provider-boundary.md) | Partially superseded | Seven static managed tools remain; runtime planning removed | diff --git a/docs/capability-migration.md b/docs/capability-migration.md deleted file mode 100644 index 1a757dd82..000000000 --- a/docs/capability-migration.md +++ /dev/null @@ -1,477 +0,0 @@ -# Incremental capability migration - -This working guide tracks the migration in #740. Update it as concrete domains -migrate. Existing public contracts and domain-specific ports remain authoritative; -there is no new universal provider interface or fixed module manifest. - -## Ownership to preserve - -| Responsibility | Current owner | Migration direction | -| --------------------------------------------- | ----------------------------------- | ----------------------------------------------------- | -| Analyst semantics and Evidence representation | domain | Keep pure and provider-neutral | -| Named public input/output contracts | contracts | Keep exact CLI/MCP meaning and complete discovery | -| Producer parsing and external tool protocols | provider adapters | Keep behind the relevant typed port | -| Shared analyst workflows | application | Share between CLI and MCP | -| Concrete provider construction | composition, MCP startup | Keep fresh typed factories at the production boundary | -| Investigation Evidence and Unknowns | InvestigationRecords/EvidenceLedger | Consume narrow read/write/atomic record ports | -| Target/profile snapshots and invalidation | BinarySessionRecords/BinarySession | Keep binary-owned | -| Subprocess ownership and host primitives | process/windows | Reuse; preserve cancellation and cleanup | -| Public translation | CLI/MCP adapters | Delegate to shared workflows and named contracts | - -Retain exact Evidence IDs, provenance, detached reads, atomic Evidence/Unknown -mutations and optimistic revisions. Preserve current close and failed-cleanup -record clearing while extracting ownership; #721 owns any retention-policy change. -Each CLI invocation and MCP connection keeps its own state. Provider registration -must not launch engines or install prerequisites. - -## Migrate before generalizing - -1. Record the actual callers, state, environment, protocol and verification owner - of the capability being migrated. -2. Move concrete construction behind its existing typed port. Preserve injected - ports, selected environment, queues, failure state and cleanup behavior. -3. Test both caller paths and the applicable package/real-provider boundary. -4. Use independently migrated capabilities to identify repeated metadata and - composition needs. Derive a small source declaration only when those needs - are established; keep unlike target/lifecycle semantics separate. -5. Move a coherent capability's files, fixtures and verification lanes in a - mechanical PR. Update all path-sensitive consumers in that same PR. - -Pure helpers do not need an interface each. A capture-format adapter or typed -factory may be sufficient. Avoid generic JSON execution, external MCP catalog -passthrough, eager provider acquisition, new permission fields or a multi-package -rewrite. Optional loading should preserve successful peers and report the failed -capability without hiding tools from the catalog. - -## Checks before and after a move - -`npm run verify:test-discovery` compares actual Vitest file discovery with every -repository-owned `*.test.ts` under src and tests, including newly added files. The -check requires Git, includes untracked non-ignored tests, and excludes removed -paths during a move. It -rejects missing files and overlapping project ownership. It only lists files; -it does not replace behavior tests or real-provider verification. - -Check imports, project isolation and coverage, development-test selection, -lint exceptions, catalog/generator imports, npm and CI verification entrypoints, -fixture ownership, and installed-package bridge/native path resolution. -Domain and contracts must not import application workflows, caller adapters or -provider implementations. Production composition is a deliberate outer boundary. -Other existing adapter imports will migrate incrementally; do not widen a lint -exception to conceal new protocol code inside application workflows. - -`npm run verify:module-boundaries` parses repository-owned source imports, -reexports, type imports and literal dynamic imports, then checks their resolved -source layer. Nested names such as `domain/android` are domain code; `src/android` -is the provider adapter. The check runs with lint, including cached static gates. -It covers tracked and untracked non-ignored TypeScript source and skips cached -paths removed during a move. Pass exact source paths for a focused check. - -Pure source and its tests keep inward dependencies. Application/server provider -construction guards cover the migrated deep, Android, firmware, JavaScript recovery and observation -implementations. Application workflows cannot import composition, including the -former binary runtime entrypoint; shared browser capture/export helpers remain admitted while their -ownership is reviewed. Test lane restrictions still use Oxlint. Producer-dependent -browser and managed comparison tests live in boundary lanes with their original -fixtures and assertions. This is a development guard, not runtime authorization. - -Select verification by the claim changed: schema/composition, package, real -engine or host-native workflow. Record host/target prerequisites and source-owned -fixtures. Run heavy lanes serially with bounded workers/heaps and reuse existing -engines. Recording ports do not prove real provider or platform support. - -## Extension examples to validate during migration - -An implementation of an existing port should require a provider adapter, typed -production factory selection, exact producer parsing/provenance and matching -verification. Existing workflow meaning and public contracts should stay stable. - -A new analyst capability deliberately adds semantics, named contracts, a typed -port/workflow when needed, both caller adapters, availability, documentation and -verification. Its integration is broader than swapping a provider. The migration -should eliminate incidental duplicate wiring, not erase those design decisions. - -Update these examples with real migrated entrypoints before closing #740. - -## First production factory migration - -`src/composition/android.ts` and `src/composition/firmware.ts` construct providers -behind the existing AndroidAnalysisPort and FirmwareAnalysisPort. CLI registrars -pass their selected environment; MCP uses the process environment unless a caller -injects a port. Each factory call returns a fresh instance and acquires no process, -workspace or toolchain. Queues, cleanup-failure state and per-request cleanup stay -inside the provider. The existing launcher seams remain available to boundary -fixtures, which now exercise the production factories. - -Application workflows and MCP registration must not import these concrete -providers. Composition may import their implementations. Binary composition also -uses this outer boundary after its direct-analysis callers were migrated. -This concrete pilot does not introduce a shared provider interface or module -manifest. - -## Independent optional observation adapters - -Browser observation, browser scenarios, Electron observation, Electron scenarios -and V8 Inspector observation now have separate factories in `src/composition/`. -CLI commands reuse them; MCP startup dynamically imports each factory independently. -`OptionalObservationProviders` describes these five existing typed ports only. It -is provisional startup wiring, not an extensible plugin manifest or a universal -provider interface. - -A failed import or constructor retains the successful peers. The complete tool -catalog remains advertised. Session availability reports the failed adapter and -its actual reason, and affected handlers return the existing capability-unavailable -error. Explicit loading failures take precedence over configured availability. -Passive Electron and active Electron failures are independent; static JavaScript -analysis and runtime reconciliation remain usable without either adapter. CLI -Electron commands also load only their selected runtime factory at execution. - -Source identities are available without importing the optional implementations. -Registration acquires no engines, probes no endpoints, changes no permissions and -installs nothing. Core transport failures and shutdown still use their existing -lifecycle. Fault-injection coverage uses the production loading/startup path and -actual MCP SDK calls; recording ports establish composition behavior, while the -real Inspector lane separately establishes runtime behavior. - -## Investigation record ownership pilot - -`src/application/investigation/InvestigationRecords.ts` owns one existing -EvidenceLedger per runtime. The production session composition constructs that -owner explicitly; the direct BinarySession constructor retains a fresh default -for compatibility. There is no second ledger, global store, persistence or new -retention policy. - -The ledger, Unknown Evidence helper and the ledger's two original behavior tests -now live beside the owner in `src/application/investigation/`. Bundle validation -and record-owner consumers follow the new paths; retained-reference access still -uses the narrow record ports. The move preserves implementation bodies and test -assertions. Binary snapshot/cache files remain with their existing owner. - -EvidenceReader, EvidenceWriter and EvidenceUnknownWriter describe existing -read/write/atomic callback needs. UnknownRegistryPort preserves optimistic -revisions and consistency verification. Non-binary MCP registrars use these -record types without depending on the binary execution/lifecycle surface. -BinarySessionPort retains its compatible record methods through composition. - -BinarySessionRecords remains the snapshot owner and compatibility facade. It -passes the actual active target explicitly for recordUnknown/updateUnknown; -recordEvidenceWithUnknown keeps its target-free mutation subject. Snapshot import -merges records without notifying midway, then emits after the cache commits. -Bundle import retains the full change delta so Unknown-only changes notify even -when recordsAdded is zero. Clearing resets records, cache and invalidation before -notification; observer failures remain best effort after a committed mutation. - -Close and failed-cleanup clearing, ordinary target-switch retention, detached -reads, Evidence identities and deterministic bundle transfer keep their existing -behavior. Snapshots still require an active target and concrete analysis profile; -extracting investigation ownership does not make them a target-free record store. -#721 remains responsible for any future lifetime-policy change. - -## Inspector adapter ownership - -`src/inspector/` owns V8 Inspector discovery, passive capture, script/target -location interpretation and its lightweight provider identity. The composition -factory and optional loader use this owner. Browser CDP connection, endpoint/value -and Electron file-location helpers remain deliberate shared adapter utilities at -their existing paths; no provider wire protocol moves into domain or process. - -Loopback fixtures and producer boundaries now live under -`tests/fixtures/inspector/` and `tests/boundary/inspector/`. The socket-backed -unresolved-target reconciliation test moves from composition into the forked -boundary lane with its original assertions. Adapter tests retain fork isolation. -`npm run verify:inspector` keeps its public development entrypoint and delegates -to `scripts/verify/inspector/runtime-observation.mjs`, using the real Node fixture -under `tests/conformance/inspector/`. Catalog imports, source guards and test -discovery follow the new paths. Observation authority, lifecycle, producer -interpretation and caller-visible contracts stay unchanged. - -## Auxiliary source declaration pilot - -Artifact, macOS native and managed static metadata now belongs to each adapter's -`*ProviderMetadata.ts` module. The implementation and -`src/composition/auxiliaryAnalysisProviders.ts` reuse the same identity and exact -capability descriptors. The declarations reference existing AnalysisProvider -loaders; they cover these three disjoint auxiliary implementations only. Deep -candidate selection and the five typed observation ports remain separate. - -The binary runtime reads these source declarations while auxiliary construction -stays lazy. The separate managed-only entrypoint retains direct construction for -its execution-free workflow. The MCP catalog generator reads declarations without -constructing implementations, using its canonical macOS platform; actual runtime -host restrictions remain explicit. -Discovery and binary operation-kind routing now consume canonical source contracts -rather than their generated JSON artifact. No declaration imports its generated -output. Generated catalog facts and public schemas stay unchanged. - -All observation registrars resolve contracts by name. An isolated compiled-process -test reverses presentation arrays and performs actual MCP SDK calls to verify -advertised schemas and handler meaning. Reordering metadata must not select a -different operation, schema, provider or deep-provider priority. - -## Android layer and verification ownership - -Android workflows and their existing typed port live in `src/application/android/`, -pure APK/inventory semantics in `src/domain/android/`, and the named inspection -contracts in `src/contracts/android/`. The headless JADX producer remains in -`src/android/`; `src/composition/android.ts` supplies its fresh factory to both -caller adapters. Public names, result meaning and JVM/queue/cleanup limits are -unchanged. Inventory-only application projection remains execution-free. - -The real lane and signal-cleanup helper belong to `scripts/verify/android/`; its -explicit downloader and fixed manifest belong to `scripts/fixtures/android/`. -`verify:android` and `fixtures:android` keep their command names and repository-root -`_reference/apk-integration/` fixture default. Synthetic producer fixtures stay in -`tests/fixtures/android/`, with matching boundary and composition ownership. Real -JADX CLI/MCP parity requires the fixed APK and existing audited JAR; synthetic -protocol/cancellation success does not establish that engine or an unverified host. - -## Deep-provider source declarations - -Hopper, Ghidra and IDA declare their implemented analyst operations in their -own `*ProviderCapabilities.ts` modules. Hopper's inventory is typed against the -existing direct-operation contracts; Ghidra reuses its inventory/function adapter -operations; IDA retains its read-only operation family. Frozen operation arrays -feed the existing capability builders without importing generated catalog data. - -The catalog generator reads these source declarations and joins operation names -to canonical `TOOL_CONTRACTS`. A missing contract identifies the declaring provider -and operation. Public schemas and descriptions remain owned by contracts; the -declarations describe implementation coverage. Provider adapters must not consume -the generated MCP catalog that is derived from them. The resolved module guard -checks this edge while admitting canonical source contracts, generated package -metadata and the existing application snapshot-cache consumer. - -Exact provider effects and lifecycle differences remain in their adapters: -Hopper's GUI and mutation effects, Ghidra's experimental Windows authority and -mutation restrictions, and IDA's attached/headless effects and live observations. -This source increment introduces no common provider lifecycle or new interface. - -## JavaScript application ownership - -`src/application/javascript/` owns JavaScript/Electron artifact analysis and -graph projection, feature/version/export/source comparisons, runtime Evidence -and reconciliation, observation ports, and source recovery workflows. Pure -analysis and public schemas keep their existing domain/contract ownership; -shared artifact inventory, investigation records and execution types remain -shared. CLI, MCP and production factories import the owning workflow directly. - -`src/domain/javascript/` owns static parsing and semantic IR, application and -semantic graphs, Electron facts, runtime reconciliation, recovery result -semantics, and source-to-bundle comparisons. Shared Evidence, digests, ordering, -comparison semantics and historical-source graphs stay at their existing owners. -Native handoffs link exact-subject Evidence without selecting or executing a -provider. - -`src/contracts/javascript/` owns the JavaScript/Electron observation and recovery -contracts, JavaScript-specific workflow requests, and their examples. The shared -`applicationToolContracts.ts` aggregate stays at the contract root because it also -owns reconstruction and Android/Apple projection operations. Canonical tool -aggregation, named handler binding and SDK schema presentation remain unchanged. -Catalog source paths, compiled verifier/SDK fixtures and recovery CI filters -follow the domain/contract owners. - -`scripts/verify/javascript/` groups application-workflow, runtime-reconciliation, -large-digest and real-recovery entrypoints. Their existing npm commands retain -their invocation semantics. Recovery fixture compilation lives beside its -unchanged sources under `scripts/fixtures/javascript-recovery/`. Its default -REA entrypoint still resolves to `scripts/rea.mjs`. Managed conformance imports -the relocated compiled workflow; owning CI source filters follow the new paths. - -`src/artifacts/javascript/` owns directory/ASAR reader construction and relevant -file acquisition, including root/nested byte verification, UTF-8 diagnostics and -nested reader cleanup. Its narrow factory returns the existing `ArtifactReader`; -the application retains input admission, inventory, graph construction and its -original root-reader `finally` close. Pure file facts live in -`src/domain/javascript/javascriptArtifactFiles.ts`, and the shared immutable -inventory snapshot lives in `src/domain/artifactInventorySnapshot.ts`. Inventory -options and integrity policy remain application-owned. Shared stream hashing -lives in `src/artifacts/ArtifactHash.ts`, preserving complete byte counts and the -bounded classification prefix. Acquisition/hash guards reject imports from -application, composition or caller adapters; JavaScript workflows use the factory -instead of importing concrete ASAR/directory reader classes. - -ZIP, native-DMG and Mach-O inventory reader selection keep their existing -lifecycles. Runtime ports retain their distinct Inspector, passive Electron and -active Electron effects; shipped Electron hooks remain at their existing -provider boundary. - -## Managed capability ownership - -`src/domain/managed/` owns managed artifact and member semantics, reconstruction -import, native-boundary verification and application graph projection. -`src/application/managed/` owns their shared Evidence workflows, and -`src/contracts/managed/` owns their named contracts and examples. Producer -metadata/IL parsing stays in `src/dotnet/`; target resolution, Evidence, ordering -and investigation records retain their shared owners. Path-based member -comparison preserves its actual target/byte-digest admission and existing parser -helper. - -`scripts/verify/managed/` groups the portable conformance entrypoint and its -support, manifest, oracle and completion-report helpers. Its PE byte fixture -builder and declaration live in `scripts/fixtures/managed/`, shared with the -installed-package lane and existing managed conformance tests. `verify:managed` -keeps its command name and optional caller-cwd manifest resolution. Compiled -catalog and generator imports follow the owners; document-check cache inputs -include the relocated runtime verifier and fixture files. - -Portable byte fixtures, optional operator-local manifests, actual ILSpy oracles -and real Ghidra NativeAOT checks retain their distinct proof levels and -prerequisites. The existing NativeAOT fixture/engine lane keeps its owner. This -move preserves implementations, Evidence identities and generated commitments. - -## Binary application ownership - -`src/application/binary/` owns the active session, deep-provider registry and -evaluation, operation routing, disjoint provider composition, lazy auxiliary -clients, cancellation and client cleanup. Its records facade and snapshot -cache/files remain bound to the exact target and analysis profile. Investigation -records still have their separate owner in `src/application/investigation/`. - -`AnalysisProvider.ts` stays shared because its identity/execution types also serve -nonbinary ports. `BinaryTargetResolver.ts` stays shared because Android, firmware, -managed and artifact workflows use its target parsing. Production wiring lives -in `src/composition/binary.ts`; application workflows gain no outward composition -dependency. - -The three colocated application tests move with their owner. Composition cases -remain in `tests/composition/analysis-sessions/`; filesystem and SDK cases retain -their boundary lanes. The shared `tests/fixtures/binarySession.ts` factory supports -several capability families. Existing recursive application globs discover the -moved tests; bridge assets and real-verifier entrypoints remain at their owners. - -## Firmware layer and verification ownership - -Firmware workflows and their existing typed port live in -`src/application/firmware/`, pure request/result semantics in -`src/domain/firmware/`, and named contracts in `src/contracts/firmware/`. -`src/firmware/` keeps producer commands, report parsing, source copies, publication -and cleanup; `src/composition/firmware.ts` supplies a fresh typed factory. - -The real lane belongs to `scripts/verify/firmware/analysis.mjs`; the fixture runner -and its unchanged Python producer belong together in `scripts/fixtures/firmware/`. -The npm command names and selected `REA_FIRMWARE_FIXTURE_ROOT` are unchanged. The -runner retains its working-directory-relative default; the verifier retains its -repository-root default. Both point to `_reference/firmware-integration/generated` -when invoked through the documented npm commands. Optional ext4/Ghidra lanes keep -their own prerequisites. Source-fixture generation and synthetic producer tests -do not establish real Binwalk/Unblob analysis or another host's execution support. - -## Apple artifact capability ownership - -`src/domain/apple/` owns Apple application anatomy/projection, asset catalog -facts, Interface Builder graphs, keyed archive semantics and plist values. -`src/application/apple/AppleApplicationService.ts` retains the shared workflow -that projects authenticated IPA/macOS inventory Evidence. - -`src/artifacts/apple/` owns the actual producer boundary: directory acquisition, -assetutil invocation, plist/NIB decoding, encoded view-parent interpretation and -keyed archive inspection. These helpers are used by ArtifactProvider, retain -its existing typed analysis boundary, injected assetutil seam and original reader -cleanup, and do not require a new port for each helper. Producer code no longer -lives in the application layer. Guards reject application/composition/caller -imports from this owner while admitting pure facts and shared artifact readers. -Adapter-source tests retain their assertions in the existing forked adapter lane. - -`scripts/verify/apple/` groups archive, asset catalog, Interface Builder, -Objective-C/Swift dispatch and macOS bundle verification. The macOS bundle fixture -builder lives in `scripts/fixtures/apple/`; NIB byte fixtures stay beside their -artifact decoder. Existing format-specific conformance sources and goldens keep -their locations, and relocated verifiers resolve them against their own file -URLs. Public npm entrypoints and CLI/MCP contracts stay stable; generated-document -cache inputs include the relocated runtime scripts and fixture builder. - -Portable decoder and injected producer tests establish their format/boundary -claims. Actual Swift/Xcode, assetutil, native NIB, bundle signing and DMG lifecycle -claims require the real Apple lane. Native binary API/value-flow semantics and -shared cross-domain contract aggregates keep their separate owners. - -## Artifact inventory and extraction ownership - -`src/artifacts/inventory/` owns format classification, reader selection, inventory -policy, canonical scanning and artifact graph construction. The shared artifact -provider and JavaScript reconstruction workflow consume this owner. Snapshot -semantics remain in `src/domain/artifactInventorySnapshot.ts`. - -`src/artifacts/extraction/` owns member selection, integrity checks and transactional -materialization through the existing readers and safe output tree. Reader cleanup, -cancellation, rollback, archive containment and caller-visible results retain their -existing behavior. Acquisition guards reject imports from these producer owners -into application workflows, production composition or CLI/MCP adapters. - -`src/application/artifacts/ArtifactExtractionDestination.ts` owns the caller's -default temporary output-root choice for both CLI and MCP. The adapters pass this -destination to the existing provider operation; format handling and member writes -remain in the artifact owner. - -Add format-specific acquisition behavior beside the inventory readers and exercise -its actual producer representation in filesystem boundary tests. Add caller -workflow behavior in the application owner and verify both adapters. The installed -package lane checks inventory identity and extraction through CLI and MCP; the -real Apple bundle lane separately establishes DMG mount and detach behavior. - -## Binary production composition closure - -`src/composition/binary.ts` is the shared production owner for deep candidate -construction, lazy auxiliary composition and the managed-only session factory. -It preserves the existing constructor bodies, selection policy and fresh session -per invocation. Factory registration acquires no engine or target. - -`DirectAnalysis` and `DirectAnalysisStatus` receive these two existing factories -through `DirectAnalysisDependencies`. They retain configuration parsing, selected -status environment, cancellation, snapshot replay/binding, Evidence projection -and finally-close. The dependency uses the existing BinarySession type, including -its replay policy; it adds no universal backend or lifecycle contract. - -`src/composition/directAnalysis.ts` binds the production factories for CLI and -one-shot managed MCP callers. Binding creates no session and stores no retained -analysis state. MCP startup constructs its connection session through the same -binary factory. Source and compiled fixtures use these entrypoints. The former -application runtime path is removed, and the source guard no longer admits its -outward provider/composition imports. - -## Native analyst capability ownership - -`src/domain/native/` owns portable native inspection, instruction/data types, -load-image facts, API boundaries, annotations, metadata recovery, UI observation -semantics and value/investigation graphs. `src/application/native/` owns shared -API projection, call routes, dispatch inspection and UI/value tracing. Its tests -keep the existing service lane. `src/contracts/native/` owns the named native -adapter contracts; shared official/enhanced aggregates remain at their owners. - -Producer interpretation, external commands and host UI lifecycle remain in -`src/native/`, Hopper, Ghidra and IDA. The shared function dossier still lives in -`domain/hopperValues.ts`: its historical name does not make its meaning exclusive -to Hopper. This move retains existing typed ports, exact result schemas, -observed/derived/unknown distinctions, profiles and Evidence links. - -Source and compiled verifier imports follow the new owners. Host UI and real -native-value verifier locations are retained until their own proof lanes migrate; -interactive macOS UI success and real dependency tracing require their respective -host/engine workflows. Portable source fixtures and injected call-route tests -establish their narrower boundaries, without expanding provider/platform support. - -## Process capture and analyst workflow ownership - -`src/domain/process/` owns scenario/capture validation, portable process trees, -trace specifications, observations, comparisons and the canonical process Evidence -identity. The standalone contract example lives in `src/contracts/process/`; -shared session contracts retain their broader investigation owner. - -`src/process/capture/` owns the actual PTY boundary, terminal rendering, sampling, -selected child environment, filesystem snapshots/effects, runtime path admission, -event journal, settlement and resource cleanup. It reuses `src/process/` ownership -primitives and the Windows host substrate. Its identity import follows the -existing pure declaration directly. A source guard rejects outward application, -composition and caller imports; no new provider or lifecycle interface is added. - -`src/application/process/` retains Evidence projection and file-backed CLI -capture/comparison workflows. Capture helper tests use the forked adapter lane; -Evidence/host integration tests use the serial process-boundary lane. Their -fixtures and assertions remain unchanged. Installed capability-probe URLs follow -the new compiled adapter path, including the optional-dependency failure probe. - -Windows PTY capture retains its existing unavailable outcome because descendant -cleanup is not yet verified. Native Job Objects and a PTY binary do not establish -that capture workflow. Real POSIX capture/cleanup and installed terminal/PTY module -resolution require their actual host and package lanes; portable comparison -fixtures establish their separate evidence semantics. diff --git a/docs/cli.md b/docs/cli.md index 51a45c462..a80339cf4 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -80,7 +80,7 @@ or close. Provider failures are returned with their original reason. For an `ambiguous` selection error, choose from `details.candidate_ids`; for `provider_unavailable`, run `rea doctor --provider ID --json` to diagnose the selected engine. See [task readiness](installation.md#check-readiness-for-your-task) -and [provider selection](adr/0001-provider-selection-and-analysis-profiles.md). +and [provider selection](mcp-contracts.md#identity-and-discovery). The session reports work still in progress through `analysis_activity`. A client timeout can end its wait while the provider continues analyzing. diff --git a/docs/ghidra-provider.md b/docs/ghidra-provider.md new file mode 100644 index 000000000..0ba061177 --- /dev/null +++ b/docs/ghidra-provider.md @@ -0,0 +1,72 @@ +# Ghidra provider semantics + +REA imports one target into an ephemeral Ghidra database. Linux/macOS support +read-only analysis and atomic function-name/entry-comment edits; Windows P0 is +read-only. GUI controls and persistent database mutation are unavailable. +Executable bytes remain unchanged. + +Use [installation](installation.md#ghidra) for supported hosts, prerequisites, +configuration, startup deadlines, resource controls, and cleanup recovery. +[Windows P0](windows-ghidra-p0.md) has its own admission and lifecycle boundary; +[NativeAOT recovery](ghidra-nativeaot.md) is an optional, separately verified +extension. Check the [release boundary](installation.md#released-package-and-main) +when using npm. + +Provider selection and profile identity follow +[MCP contracts](mcp-contracts.md#identity-and-discovery). One deep +provider stays bound to the target; runtime failure never selects another +provider automatically. The contracts below describe Ghidra observations, +not equivalence with another engine's pseudocode or analysis database. + +## Admitted inventory semantics + +| Concern | Ghidra contract | +| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Program identity | One `analyzeHeadless` import produces exactly one Program; `list_documents` therefore returns exactly one name. | +| Addresses | Default memory uses lowercase `0x` hexadecimal. Non-default and external spaces use `:0x` and remain round-trippable. The handshake commits image base and default address-space name. | +| Symbols | `list_names` includes address-bearing memory and external symbols, including dynamic symbols, while excluding variable and no-address namespace records. Each item reports primary, dynamic, external, symbol type, and source facts. | +| Procedures | Both non-external and external functions are listed. A local thunk remains distinct from its resolved target; exact and qualified name lookup fails on ambiguity rather than guessing. | +| Strings | Only Ghidra-defined string `Data` is observed. Items report charset, byte length, and whether a required null terminator is missing. The API cannot distinguish a present terminator from fixed/Pascal layouts when no terminator is missing, so that state is named `present_or_not_required`. | +| Memory | Memory-block end addresses are exclusive. Read/write/execute, initialization, overlay, address space, and image base are direct Ghidra observations. | +| Inventory | Procedure, symbol, and string listings plus searches return the complete matching collection in one response; callers do not provide offsets or result-count limits. | +| Search | Literal and Java-regex searches scan the complete immutable inventory and return all matching entries inline. Search waits for a reply or caller cancellation; there are no caller-supplied offsets or result-count limits. | +| Analysis state | The socket is exposed only after default auto-analysis completes. Established operations wait for their reply or caller cancellation; there is no fixed response-size ceiling. | + +## Admitted function-analysis semantics + +| Concern | Ghidra contract | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Decompiler lifetime | One persistent `DecompInterface` is opened for the imported Program and disposed during bridge shutdown. Native decompilation has no fixed per-function deadline. External functions or functions without bodies return `null`; cancellation and native failure remain distinct. | +| Serialization | A FIFO sends one Program request at a time. Caller cancellation removes queued work promptly and is passed to active socket waits. This is an adapter safety commitment, not a claim that every Ghidra API is thread-safe. | +| Function identity | Every function result carries the entry address and Ghidra FunctionManager classification for external, thunk, and resolved thunk target. These are observations, not proof that unresolved targetless calls have been recovered. | +| Assembly and pseudocode | Assembly is complete Ghidra Listing text; pseudocode is Ghidra decompiler output. Neither is original source, and cross-provider comparison never treats Hopper and Ghidra text as equal or unequal semantic facts. | +| Instruction fast path | `read_function_instructions` returns every raw Listing instruction for the requested function without invoking the decompiler or whole-program name/string inventories. | +| Calls and references | Callers/callees contain only resolved functions. Reference edges preserve exact ReferenceManager type and call/jump/data/read/write/indirect/computed/conditional/terminal/external facts. Targetless computed flow remains unknown. Synthetic entry-point references without actionable memory sources are omitted explicitly. | +| CFG | Dossiers use `BasicBlockModel` and retain only non-call successors inside the function body. CFG topology is address-normalized for comparison; provider-specific block construction remains a declared difference. | +| P-code value flow | Function dossiers include up to 3,000 high-p-code operations, at most 64 inputs per operation, and 12,000 def-use edges. Results identify memory reads/writes, branches, and calls by p-code opcode, and mark decompiler-dead operations. Large results report truncation, an omitted-operation lower bound, and known omitted-input/edge counts. The dossier is an intra-function graph; `trace_native_values` composes derived parameter/argument and return/output dependencies across resolved calls. It does not resolve memory aliasing, call side effects, runtime behavior, persistent state, or business meaning. | +| Result extent | Function instruction scans and native API boundary observations remain complete. P-code flow is the explicit bounded exception; its count fields distinguish exact retained counts from lower-bound or known-omitted counts. Caller cancellation and provider failures remain distinct. | + +`npm run verify:ghidra` compiles the versioned C oracle into debug and stripped +host-native targets (x86-64/AArch64 ELF on Linux or Mach-O on macOS), plus a native +DWARF 4 type-layout object. It proves the admitted operations, external functions, resolved thunks, exports, stripped-name +behavior, direct and targetless indirect calls, typed references, strings/xrefs, +multi-block CFG, bounded p-code def-use/effect links, semantic enhanced workflows, cancellation, startup deadlines, +serialized concurrency, malformed-target rejection, profile identity, and +process/project cleanup against real Ghidra 12.1.4. Unit fixtures separately +cover startup deadlines, process exit, queued cancellation, and malformed wire +output. + +`npm run verify:ghidra:cross-format` adds AArch64 ELF, x86-64 PE, and x86-64 +Mach-O target coverage. It requires `clang`, LLD, and `lld-link`; set +`REA_CLANG`, `REA_LLD`, or `REA_LLD_LINK` to select them. The verifier checks +these tools before compilation. Keeping this matrix separate lets Linux +host/provider acceptance run with only the host compiler. + +`npm run verify:ghidra:windows` and its `-- --x86` variant check the source-owned native x86 and x86-64 PE +fixture, all 25 read-only operations, target/snapshot/import SHA-256 linkage, +and project, endpoint, process, and runtime cleanup. The independent native +lane checks DACLs, handle admission, cancellation, and Job Object lifecycle. +`npm run verify:ghidra:windows:package` packs and installs REA into an isolated +prefix, then checks ordinary-user CLI/MCP operations against canonical contracts. +All lanes require matching native controls; package startup alone establishes +only package compatibility. diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.md index 92bc23060..74e11e55e 100644 --- a/docs/managed-code-analysis.md +++ b/docs/managed-code-analysis.md @@ -1,4 +1,4 @@ -# Managed-code analysis and planned extensions +# Managed-code analysis REA inspects .NET PE/CLI artifacts without loading or executing their code. It can identify an assembly, inspect metadata and CIL, compare members across @@ -20,12 +20,11 @@ The seven shipped tools are: Each has a matching CLI command: replace underscores with hyphens and prefix the name with `rea`, for example `rea inspect-managed-artifact`. -Native-body bridge mapping remains planned; managed runtime execution is not -part of the current tool set. +Native-body bridge mapping and managed runtime execution are outside the +current tool set. -This guide describes the implementation and verification of -[ADR-0003](adr/0003-managed-code-evidence-and-provider-boundary.md). The canonical -tool inventory is the [build-generated catalog](mcp-contracts.md#generated-catalog). +The canonical tool inventory is the +[build-generated catalog](mcp-contracts.md#generated-catalog). ## Shipped scope @@ -36,10 +35,8 @@ NativeAOT identity from an ordinary native PE. Inputs without admitted CLI metadata do not become managed assemblies through naming or routing guesses. Inspect separately obtained components explicitly and preserve their identities. -The broader deployment classification and native-body mapping below are design -goals from ADR-0003, not claims that every row has an implemented parser. A -valid marker can establish a candidate native boundary, not recovered native -semantics or runtime behavior. +A valid implementation marker establishes a candidate native boundary, not +recovered native semantics or runtime behavior. ## Analysis objective @@ -57,40 +54,7 @@ collapsing them: The ordinary workflow ends at question four. Static analysis never loads or executes the target. -## Planned deployment classification - -The intended extended classifier proceeds from outermost authenticated bytes inward: - -```text -source path - -> canonical path, size, SHA-256 - -> container inventory - -> PE/native header and architecture - -> CLI header and metadata root - -> deployment/runtime markers - -> per-component and per-method implementation availability - -> managed-only, native-only, composed, degraded, or unsupported route -``` - -The planned result is a vector rather than one label. For example, a single-file modern -.NET deployment can contain a native host, ordinary CIL assemblies, and -ReadyToRun components. Each component receives its own digest, classification, -coverage, and route while retaining the outer bundle commitment. - -| Case | Required positive observations | Claims that remain unavailable or inferred | -| --------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| .NET Framework | Valid CLI metadata plus bounded Framework-specific target/reference evidence | Exact installed CLR and runtime behavior | -| Modern .NET | Valid CLI metadata plus bounded target/reference/runtime-config evidence | Exact runtime selected on another host | -| Unity Mono | Valid managed assembly plus authenticated Unity context when supplied | Engine behavior or native integration not represented by metadata | -| ReadyToRun | Valid managed metadata plus authenticated ReadyToRun header/sections | Native implementation semantics until a selected deep provider analyzes them | -| C++/CLI | Valid CLI metadata plus mixed-mode PE/header evidence | Mapping managed declarations to native implementations without explicit bridge evidence | -| Single-file | Valid authenticated bundle inventory and component extents | Components that are compressed or encoded by an unsupported bundle version | -| Unity IL2CPP | Authenticated native image/metadata pairing and supported metadata version | Canonical CIL and source-equivalent C# | -| NativeAOT | Native image plus bounded NativeAOT evidence | Ordinary CLI metadata/CIL unless independently present | -| Obfuscated assembly | Same positive byte observations as its underlying deployment form | Meaning inferred only from names | -| Malformed/unsupported | Exact admitted regions and failure locations | Completeness, successfully skipped rows, or semantics beyond the admitted parser boundary | - -### NativeAOT metadata recovery +## NativeAOT metadata recovery NativeAOT removes the ordinary CIL method bodies, so a CIL decompiler cannot reconstruct those bodies as C# source. The executable remains a native target @@ -110,28 +74,17 @@ lists supported OS/architecture targets and deployment limitations, while its [native library guide](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/libraries) describes exported shared-library entry points. -The [Ghidra NativeAOT analyzer](https://github.com/Washi1337/ghidra-nativeaot) -is a useful optional companion for recovering ReadyToRun metadata. It -rehydrates the `DEHYDRATED_DATA` section and annotates method tables, type -relationships, vtable slots, frozen objects, and strings. It does not recover -original C# method bodies. It is a separate Ghidra extension and interactive -metadata browser; REA does not currently install or invoke it through its -headless bridge. Its README describes ReadyToRun header discovery, including -symbol-based and heuristic paths, so a missed header or unsupported binary -should remain an explicit limitation rather than a failed claim about the -binary's contents. +REA supports an optional headless adapter for the Ghidra NativeAOT analyzer. +Supply a locally built `REA_GHIDRA_NATIVEAOT_JAR`; REA does not install the +extension or its toolchain. The verified boundary is .NET 8.0.22 RTR 9.1, +x86-64 ELF and native Windows PE targets analyzed on Linux x64 with Ghidra +12.1.4 and JDK 21. Other layouts, architectures, and hosts are unsupported. +See [NativeAOT recovery](ghidra-nativeaot.md) for build/configuration, recovered +metadata, derived-memory provenance, and the real verification lane. -The upstream analyzer currently gates its own analysis to x86-64. NativeAOT's -broader platform matrix does not establish REA coverage: PE/COFF, ELF, Mach-O, -shared libraries, target architectures, and runtime metadata versions each need -their own provider verification. REA's experimental Windows Ghidra boundary is -limited to admitted native x86 and x86-64 PE applications, so it does not currently -establish coverage for PE DLLs. Mobile NativeAOT targets should remain -experimental until REA has a matching provider and package-level verification. - -For REA's native analysis, preserve the same artifact path and digest used by -`inspect_managed_artifact`, and report recovered type data as provider -observations. Linking those types to native function addresses requires verified +For NativeAOT analysis, preserve the selected native artifact's path and digest +and report recovered type data as provider observations. Linking those types +to native function addresses requires verified provider evidence; names or vtable similarity alone do not prove that a native function implements a specific managed method. @@ -143,43 +96,18 @@ matches the normalized artifact SHA-256. A valid Evidence ID alone does not establish that those two identities agree. Evidence without a subject remains usable, with no subject digest available to cross-check. -Every planned operation returns a provider result and Evidence with four -commitment groups: +Artifact inspection returns the selected path, byte length and SHA-256, observed +PE/CLI classification, assembly and module identities, and metadata coverage. +Member inspection binds build-local tokens, signatures, row offsets, method +bodies, and decoded relationships to that artifact and MVID. Missing or malformed +facts remain explicit in coverage and per-member status. -### Artifact commitment +CLI `#GUID` heap values retain their exact 16-byte GUID text. REA does not impose +RFC 4122 UUID version or variant bits on MVID, EncId, or EncBaseId because +ECMA-335 metadata does not require those bit patterns. Tokens and RVAs are +build-local coordinates, not durable cross-build identities or native addresses. -- canonical local path, byte length, and SHA-256; -- outer-container identity and digest when inspecting a component; -- component name/path, byte extent, and SHA-256; -- observed PE machine, CLI flags, and conflicts; -- classification vector, supporting observations, and unresolved dimensions. - -### Module commitment - -- assembly simple name, version, culture, public-key/token state, flags, and - hash algorithm; -- module name, generation, and MVID; -- target framework and runtime/version strings with their exact metadata - locations; -- provider identity, analysis-affecting parameters, and their profile digest. - -CLI `#GUID` heap values are committed as their exact 16-byte GUID text. REA -does not impose RFC 4122 UUID version or variant bits on MVID, EncId, or -EncBaseId because ECMA-335 metadata does not require those bit patterns. - -### Entity commitment - -- table kind and build-local token; -- declaring scope and normalized CLI signature; -- row/heap/body locations expressed as typed file offsets, RVAs, or CIL - offsets; -- exact raw bytes or bounded value digest; -- raw CIL digest plus separately reported method-header, locals-token, and - exception-region observations where available; -- a deterministic decoded-instruction-tuple digest for completely decoded - CIL, with the limitations below. - -### Shipped decoded-CIL fingerprint +## Decoded-CIL fingerprint `inspect_managed_members` exposes two method CIL hashes with different byte boundaries: @@ -208,9 +136,7 @@ reproducible decoded-tuple fingerprint, not a canonical semantic CIL identity: it does not resolve tokens across MVIDs, does not commit full control flow or exception semantics, and does not replace the raw CIL digest. Cross-build comparison uses the value only as one unique-only structural tier and reports -ambiguity when that evidence is insufficient. A future normalized-CIL -commitment would need canonical token/literal identities, -complete branch and switch targets, and explicit locals/exception semantics. +ambiguity when that evidence is insufficient. For example, a decoded `nop; ret` body serializes exactly as `[["nop","none",null],["ret","none",null]]` and has digest @@ -218,73 +144,10 @@ For example, a decoded `nop; ret` body serializes exactly as This vector specifies the tuple order, `null` handling, absence of whitespace, UTF-8 encoding, and lowercase hexadecimal output. -### Epistemic commitment +## Member comparison -- authority: static bytes, reconstruction, structural inference, independent - validation, native provider, or future runtime observation; -- state: observed, inferred, unknown, or unavailable; -- confidence independent of authority; -- coverage and admitted/dropped counts; -- exact supporting Evidence IDs and actionable limitations. - -A semantic label such as `score_submission_gate` can annotate an entity, but it -is never the entity's identity. The same applies to an obfuscated name, token, -RVA, or decompiler-generated local name. - -## Planned static capabilities - -The caller-visible grouping and exact tool names are decided with the contracts -that implement them. The underlying capability slices are: - -1. **Triage and inventory**: container/component classification, assembly and - module identity, references, files, exported types, resources, attributes, - and runtime markers. -2. **Member inventory**: file-backed types, methods, fields, properties, events, - interfaces, nesting, generics, and normalized signatures. -3. **Method inspection**: headers, max stack, locals, CIL instructions, - constants, metadata operands, exception regions, and implementation flags. -4. **Relationships**: declared overrides, interface implementations, member - references, direct CIL callers/callees, field access, construction, and - interop declarations. Dynamic dispatch remains qualified. -5. **Structural search and comparison**: signature/API/constant/flow anchors, - exact and normalized hashes, competing candidates, and explicit - exact/structural/missing/ambiguous states. -6. **Managed/native composition**: P/Invoke, unmanaged exports, COM/mixed-mode - declarations, ReadyToRun/native bodies, single-file hosts, and authenticated - IL2CPP pairs linked to selected Hopper/Ghidra evidence. The shipped - verification workflow checks P/Invoke declarations against supplied native - export or function Evidence; native-body, thunk, and token-to-address bridge - mapping remain unavailable without explicit provider-supported evidence. -7. **Application graph projection**: managed assembly/module/type/method/field, - P/Invoke, and native-implementation declarations enter the same - Evidence-backed application graph vocabulary as JavaScript/Electron - findings while preserving managed static-analysis authority. - -Inventory lists preserve deterministic order and include every fact available -from the admitted PE/CLI streams. Malformed ranges and unsupported metadata are -reported as coverage issues instead of being silently omitted. Search exposes -scanned, matched, returned, and dropped counts. An unresolved indirect call or -a failed signature decode is not silently omitted from a completeness claim. - -## Obfuscation-resistant method slices - -Names are one weak feature among many. A behavior slice records the smallest -bounded set of observations needed to investigate a proposition: - -- normalized declaring/member signatures and inheritance/interface shape; -- framework and application API references; -- exact strings, numeric constants, enum-like values, and serialization keys; -- branch, switch, exception, loop, call, and field-flow shape; -- construction and generic-instantiation sites; -- raw CIL and decoded-tuple commitments, plus separate header, locals, and - exception observations; -- callers, callees, shared fields, and competing candidates; and -- limitations from reflection, dynamic dispatch, generated code, protection, - native transitions, or incomplete coverage. - -The workflow produces separate observation, inference, validation, and unknown -tables. It may say that a method is a strong candidate for a role; it cannot -turn that role into the method's durable identity. +Names and semantic labels do not establish durable member identity. Comparison +preserves observed differences, structural inferences, and unknowns separately. Cross-version matching first prefers exact CIL/signature identity. When that does not match, it pairs an exact declared type, method name, and raw signature @@ -310,16 +173,14 @@ Tokens are always remapped through observed structure. A caller cannot carry ## Managed/native boundary rules -| Boundary | Managed observation | Native observation | Permitted link | -| ----------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------- | -| P/Invoke | Module, entry point, charset/calling-convention flags, declaring method | Import/export/symbol/function evidence from the selected deep provider | Exact declared-name/module link or qualified resolution inference | -| COM | Interop attributes, GUIDs, imported interfaces, method signatures | Native registration/vtable evidence when independently available | Identifier/signature inference with explicit environment limitations | -| C++/CLI | Managed declaration and implementation flags | Native body/function evidence | Only a provider-supported bridge observation; never token-as-address | -| ReadyToRun | Component/header and per-method CIL/native availability | Native section/function evidence | Authenticated image mapping with format/profile version | -| Unmanaged export | Export metadata/attribute when present | PE export and native thunk/function | Exact export identity plus provider-qualified address | -| Single-file host | Bundle entry/component identity | Host and native component evidence | Outer bundle plus component digest/extent commitment | -| Unity IL2CPP | Supported metadata entity with authenticated pairing | Generated native function/type evidence | Versioned IL2CPP mapping only; no invented CIL | -| Runtime-resolved native | API/constant/data-flow candidate | Loaded-module/symbol observation from an independently collected runtime source | Static candidate remains inference until separately observed | +`verify_managed_native_boundaries` compares declared P/Invoke module and entry +point identities with supplied native export or function evidence. Name/module +matches establish declaration links; they do not establish that a call executed. + +Metadata tokens are not native addresses. Native body mapping for C++/CLI, +ReadyToRun, NativeAOT, and IL2CPP requires separately verified format and provider +support. The managed static tools do not recover those mappings. The optional +[Ghidra NativeAOT extension](ghidra-nativeaot.md) has its own supported boundary. Declared import inventory supports a bounded positive claim. Its absence does not exclude dynamic resolution, generated code, protected code, native helpers, @@ -333,16 +194,12 @@ fixtures and expected semantic facts. An optional real ILSpy lane runs only when its executable is explicitly supplied; the default lane does not establish independent pinned-oracle parity. Production inspection needs none of those tools. -- A pinned `System.Reflection.Metadata` differential oracle is planned; it is - not part of the current verifier. - `ICSharpCode.Decompiler`/`ilspycmd` can supply reconstruction inference. A BYO reconstruction import records the supplied version and remains non-canonical. When `REA_ILSPY_CMD_PATH` points to an absolute runnable `ilspycmd`, `verify:managed` runs a source-owned real ILSpy oracle and imports its C# output as reconstruction inference against exact static member Evidence. -- dnlib and Mono.Cecil are potential future differential oracles. Their mutation APIs - are not exposed or included in the production parsing boundary. - The package contains no .NET runtime, SDK, ILSpy installation, proprietary assembly, or compiled conformance fixture. - Setup never installs or upgrades those tools. Doctor may inspect an explicit @@ -360,29 +217,15 @@ they do not claim that the REA application itself supports Windows. Native ReadyToRun, C++/CLI, NativeAOT, or IL2CPP coverage is additionally constrained by the selected Hopper/Ghidra host and format matrix. -## Source-built conformance corpus +## Conformance verification The current lane uses source-owned byte-built fixtures and malformed-input regressions, with optional operator-supplied applications and ILSpy verification. -The table below describes the desired expanded corpus; it is not a report that -all compiler-generated forms have been independently verified. -Fixture sources are intentionally small and behavior-focused. Build outputs -are generated outside tracked fixture directories and must not remain after -verification or packaging. - -| Corpus slice | Required properties | -| ---------------------- | ------------------------------------------------------------------------------------------ | -| Identity | Assembly/module/version/culture/public key, references, attributes, resources, MVID | -| Signatures | Nested/generic types, arrays, pointers, by-ref, function pointers where supported, varargs | -| CIL | Short/long branches, switch, prefixes, constants, locals, calls, fields, boxing, tokens | -| Exceptions | Catch, finally, fault/filter where the compiler/toolchain supports them | -| Generated structure | Async and iterator state machines, lambdas, closures, properties, events | -| Interop | P/Invoke flags, module/name mapping, managed/unmanaged implementation metadata | -| Architecture | AnyCPU, preferred-32-bit where applicable, x86, x64 | -| Obfuscation resistance | Unicode/meaningless/duplicate-looking names and structure-preserving renames | -| Cross-build comparison | At least two builds with changed MVID/token order/layout and known same/changed behaviors | -| Malformed/adversarial | Truncated/overflowing headers, streams, tables, heaps, signatures, bodies, and EH sections | +Run the deterministic lane with `npm run verify:managed`. See +[testing](testing.md#real-toolchain-verification-lanes) for prerequisites and +coverage. Generated outputs belong outside tracked fixture directories and must +not remain after verification or packaging. Verification compares semantic facts, not decompiler text. It checks resource ceilings, deterministic ordering, complete cleanup, CLI/MCP parity, Evidence @@ -492,32 +335,7 @@ evidence is collected. A direct process capture can retain declared inputs, outputs, filesystem and protocol activity for a target run; it does not prove which managed methods executed or how the CLR resolved them. -## Delivery sequence - -The managed-code track advances as reviewable pull requests: - -1. accepted evidence/provider boundary (this document and ADR); -2. read-only artifact triage and exact identity (shipped); -3. file-backed metadata, signatures, method bodies, raw CIL hashes, and the - decoded-instruction-tuple fingerprint (shipped; complete normalized-CIL - semantics remain planned); -4. obfuscation-resistant slices and cross-version comparison (shipped for - static member observations); -5. decompiler reconstruction import (shipped as analyst inference; REA does - not run ILSpy/dnSpy, and metadata/CIL remain canonical); -6. managed/native composition and truthful deployment degradation (declaration - inventory and native export/function Evidence matching shipped; native-body - bridge mapping remains planned); -7. source-built managed conformance and package/CLI verification (source-owned - PE/CLI corpus shipped through `npm run verify:managed`; optional BYO - `ilspycmd` real-tool oracle shipped through `REA_ILSPY_CMD_PATH`; dnSpy and - pinned Windows checks remain planned); and -8. managed static Evidence projection into the application graph (shipped). - -Each implementation PR updates generated product facts only for behavior it -actually ships and states which real-tool checks were performed. - -### Method metadata during build comparison +## Method metadata during build comparison Managed member comparisons report a `metadata` dimension when an observed MethodDef flags or implementation flags value differs, including accessibility diff --git a/docs/provider-evaluation.md b/docs/provider-evaluation.md deleted file mode 100644 index 8aa655e52..000000000 --- a/docs/provider-evaluation.md +++ /dev/null @@ -1,219 +0,0 @@ -# Static-analysis provider evaluation - -This guide describes repository main. Check the [released package boundary](installation.md#released-package-and-main) when using npm. - -Ghidra read-only analysis is available on Linux x64/arm64 and macOS x64/arm64. -Install a Ghidra 12.1.x release and the 64-bit full JDK that release declares, -then configure REA to use them. Current 12.1 releases require JDK 21 or newer -and set no maximum. The bridge is verified with Ghidra 12.1.4 and JDK 21. -Each installation needs the matching native decompiler. - -REA imports one target into a temporary project and exposes 25 read-only -operations after analysis completes. They cover inventories, search, -decompilation, assembly, function metadata, resolved calls, references, control -flow, instructions, and recovered types. Results identify the provider version, -analysis settings, target digest, and any unavailable or incomplete facts. -On Linux and macOS, `annotate_native_function` additionally edits names and entry -comments atomically, verifies readback, and returns refreshed function analysis. -Changes live only in the session database and leave executable bytes unchanged. -Ghidra does not expose GUI controls; Windows P0 remains read-only. - -Windows x64 P0 supports native x86 and x86-64 PE applications on local NTFS with -bundled Job Object ownership, protected runtime DACLs, and handle-based path -admission. Real ordinary-user verification covers all 25 read-only operations -through the packaged CLI and MCP, target integrity, and cleanup. This remains -an experimental boundary; see [Windows Ghidra P0](windows-ghidra-p0.md) and -[issue #527](https://github.com/morluto/rea/issues/527). - -[ADR-0001](adr/0001-provider-selection-and-analysis-profiles.md) fixes the -provider registry, deterministic selection, target binding, analysis profile, -snapshot migration, and compatibility semantics that implementation must -follow. - -## Approved Ghidra v1 boundary - -- Keep the existing provider-neutral CLI and MCP tool names. -- Bind one deep-analysis provider to a target for the target's lifetime; never - fail over silently between Hopper and Ghidra. -- Use an existing Ghidra installation and a compatible Java runtime. Setup must - not install or upgrade Ghidra or Java. -- Run Ghidra headlessly in an owned process with a private temporary project, - startup and cleanup deadlines, caller cancellation, and complete replies. -- Prefer a packaged Java bridge loaded through Ghidra's script path. PyGhidra - remains useful for prototypes but is not a mandatory production dependency. -- Treat authenticated `ping` and `shutdown` as lifecycle proof only. Inventory, - xref, CFG, and decompilation claims require separately admitted operation - contracts and real-provider conformance. -- Implement read-only inventories, assembly, decompilation, function metadata, - calls, references, containment, and complete inventory search first. -- Report GUI cursor/navigation and persistent mutation operations as unavailable - until their semantics and project ownership are explicitly designed. -- Verify real claims on Linux with at least two distinct source-owned binaries. - Verify the Windows host claim with the deterministic source-owned x86 and x86-64 PE - fixtures and all admitted operations; compare normalized semantic facts rather - than provider-specific pseudocode text. - -## Shipped foundation boundary - -`GHIDRA_INSTALL_DIR` must identify an extracted Ghidra 12.1.x release. Optional -`JAVA_HOME` must identify a 64-bit full JDK inside that installation's -`application.java.min` and `application.java.max` (JDK 21 or newer, with no -maximum, when the release leaves those at the 12.1 defaults). Otherwise doctor -probes `java`/`javac` or `java.exe`/`javac.exe` from `PATH`. Supported Linux and macOS -hosts accept compatible ELF, PE, and Mach-O executable targets. Host admission -and target compatibility are separate checks. Windows x64 P0 admits only native, -non-managed, non-DLL x86 and x86-64 PE applications on fixed local NTFS, with the packaged -native authority available before launch. - -The launcher creates one ephemeral runtime root with project, -home/cache/config/data/temp, logs, descriptor, endpoint, target snapshot, and -ownership manifest. -It passes `-readOnly` and `-deleteProject`, and uses Ghidra's default analysis -and resource settings; inherited Java option injection variables are cleared. -On Linux, the mode-0600 descriptor carries the random token without -exposing it in argv or environment and the Java bridge binds a mode-restricted -Unix socket. macOS uses the same local transport. The bridge reports actual -Ghidra/language/compiler/analysis/import-digest metadata and accepts only -authenticated `ping`, `shutdown`, thirteen read-only inventory/load-image methods, -and twelve function-analysis methods. Linux/macOS also admits atomic function -annotation changes in the ephemeral database. Close, cancellation, timeout, malformed protocol, -or process exit stops the owned process resources, closes the socket, and -removes the runtime root. - -The experimental Windows transport uses authenticated IPv4 loopback with a -token-free endpoint record. The bundled native authority establishes Job Object -ownership, protected runtime DACLs, and handle-based path admission before -launch. If the bundle or an admission constraint is unavailable, the provider -remains unavailable; a `taskkill` fallback does not establish that authority. - -The provider catalog lists 25 read-only Ghidra operations and the Linux/macOS -session annotation operation. GUI cursor/navigation and persistent mutations -remain unavailable; Windows P0 admits no database mutation. The router therefore -reports them unavailable instead of borrowing Hopper semantics or inferring -capability from a successful import. - -## Admitted inventory semantics - -| Concern | Ghidra contract | -| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Program identity | One `analyzeHeadless` import produces exactly one Program; `list_documents` therefore returns exactly one name. | -| Addresses | Default memory uses lowercase `0x` hexadecimal. Non-default and external spaces use `:0x` and remain round-trippable. The handshake commits image base and default address-space name. | -| Symbols | `list_names` includes address-bearing memory and external symbols, including dynamic symbols, while excluding variable and no-address namespace records. Each item reports primary, dynamic, external, symbol type, and source facts. | -| Procedures | Both non-external and external functions are listed. A local thunk remains distinct from its resolved target; exact and qualified name lookup fails on ambiguity rather than guessing. | -| Strings | Only Ghidra-defined string `Data` is observed. Items report charset, byte length, and whether a required null terminator is missing. The API cannot distinguish a present terminator from fixed/Pascal layouts when no terminator is missing, so that state is named `present_or_not_required`. | -| Memory | Memory-block end addresses are exclusive. Read/write/execute, initialization, overlay, address space, and image base are direct Ghidra observations. | -| Inventory | Procedure, symbol, and string listings plus searches return the complete matching collection in one response; callers do not provide offsets or result-count limits. | -| Search | Literal and Java-regex searches scan the complete immutable inventory and return all matching entries inline. Search waits for a reply or caller cancellation; there are no caller-supplied offsets or result-count limits. | -| Analysis state | The socket is exposed only after default auto-analysis completes. Established operations wait for their reply or caller cancellation; there is no fixed response-size ceiling. | - -## Admitted function-analysis semantics - -| Concern | Ghidra contract | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Decompiler lifetime | One persistent `DecompInterface` is opened for the imported Program and disposed during bridge shutdown. Native decompilation has no fixed per-function deadline. External functions or functions without bodies return `null`; cancellation and native failure remain distinct. | -| Serialization | A FIFO sends one Program request at a time. Caller cancellation removes queued work promptly and is passed to active socket waits. This is an adapter safety commitment, not a claim that every Ghidra API is thread-safe. | -| Function identity | Every function result carries the entry address and Ghidra FunctionManager classification for external, thunk, and resolved thunk target. These are observations, not proof that unresolved targetless calls have been recovered. | -| Assembly and pseudocode | Assembly is complete Ghidra Listing text; pseudocode is Ghidra decompiler output. Neither is original source, and cross-provider comparison never treats Hopper and Ghidra text as equal or unequal semantic facts. | -| Instruction fast path | `read_function_instructions` returns every raw Listing instruction for the requested function without invoking the decompiler or whole-program name/string inventories. | -| Calls and references | Callers/callees contain only resolved functions. Reference edges preserve exact ReferenceManager type and call/jump/data/read/write/indirect/computed/conditional/terminal/external facts. Targetless computed flow remains unknown. Synthetic entry-point references without actionable memory sources are omitted explicitly. | -| CFG | Dossiers use `BasicBlockModel` and retain only non-call successors inside the function body. CFG topology is address-normalized for comparison; provider-specific block construction remains a declared difference. | -| P-code value flow | Function dossiers include up to 3,000 high-p-code operations, at most 64 inputs per operation, and 12,000 def-use edges. Results identify memory reads/writes, branches, and calls by p-code opcode, and mark decompiler-dead operations. Large results report truncation, an omitted-operation lower bound, and known omitted-input/edge counts. The dossier is an intra-function graph; `trace_native_values` composes derived parameter/argument and return/output dependencies across resolved calls. It does not resolve memory aliasing, call side effects, runtime behavior, persistent state, or business meaning. | -| Result extent | Function instruction scans and native API boundary observations remain complete. P-code flow is the explicit bounded exception; its count fields distinguish exact retained counts from lower-bound or known-omitted counts. Caller cancellation and provider failures remain distinct. | - -`npm run verify:ghidra` compiles the versioned C oracle into debug and stripped -host-native targets (x86-64/AArch64 ELF on Linux or Mach-O on macOS), plus a native -DWARF 4 type-layout object. It proves the admitted operations, external functions, resolved thunks, exports, stripped-name -behavior, direct and targetless indirect calls, typed references, strings/xrefs, -multi-block CFG, bounded p-code def-use/effect links, semantic enhanced workflows, cancellation, startup deadlines, -serialized concurrency, malformed-target rejection, profile identity, and -process/project cleanup against real Ghidra 12.1.4. Unit fixtures separately -cover startup deadlines, process exit, queued cancellation, and malformed wire -output. - -`npm run verify:ghidra:cross-format` adds AArch64 ELF, x86-64 PE, and x86-64 -Mach-O target coverage. It requires `clang`, LLD, and `lld-link`; set -`REA_CLANG`, `REA_LLD`, or `REA_LLD_LINK` to select them. The verifier checks -these tools before compilation. Keeping this matrix separate lets Linux -host/provider acceptance run with only the host compiler. - -`npm run verify:ghidra:windows` and its `-- --x86` variant check the source-owned native x86 and x86-64 PE -fixture, all 25 read-only operations, target/snapshot/import SHA-256 linkage, -and project, endpoint, process, and runtime cleanup. The independent native -lane checks DACLs, handle admission, cancellation, and Job Object lifecycle. -`npm run verify:ghidra:windows:package` packs and installs REA into an isolated -prefix, then checks ordinary-user CLI/MCP operations against canonical contracts. -All lanes require matching native controls; package startup alone establishes -only package compatibility. - -## Shared provider-process foundation - -`src/process/` now provides the mechanisms that a long-lived Hopper or Ghidra -adapter shares: POSIX run-token-authenticated process-group ownership, -ephemeral temporary runtime roots, one absolute startup deadline, correlated -request cancellation and lifecycle-deadline cleanup, bounded stdout and stderr retention with -exact byte counts, process-exit diagnostics, and bounded TERM-to-KILL shutdown. -Reusable fixtures exercise exit, timeout, cancellation, graceful termination, -forced termination, double-close, spawn failure, and resource release. Windows -Ghidra uses its native Job Object, private runtime, and path-admission boundary; -generic process-tree termination alone cannot establish provider availability. - -The foundation does not define a bridge schema, socket framing, health payload, -analysis model, or shutdown acknowledgement. Hopper keeps its authenticated -NDJSON-over-Unix-socket protocol in `src/hopper/`; Ghidra has a separate strict -NDJSON protocol implemented by the packaged Java `HeadlessScript` and reuses -only the generic process mechanisms. - -## Shortlist - -| Provider | License / automation surface | What it brings | REA fit and blockers | -| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Ghidra](https://github.com/NationalSecurityAgency/ghidra) | Apache-2.0 source license; `analyzeHeadless`, Java APIs, and PyGhidra | Static analysis, multiple processors and formats, scripting, and project/database workflows | 25 read-only operations shipped on Linux/macOS with installation checks, temporary projects, a serial API queue, and real ELF/PE/Mach-O conformance. Experimental Windows x64 P0 supports native x86 and x86-64 PE on local NTFS with bundled native controls and ordinary-user CLI/MCP verification; Linux/macOS additionally support atomic session function annotations; Windows mutation and all Ghidra GUI operations are unavailable. | -| [Rizin](https://github.com/rizinorg/rizin) / [rz-pipe](https://github.com/rizinorg/rz-pipe) | Rizin repository contains LGPL-3.0 and GPL-3.0 components; `rizin`, `rz-bin`, and language bridges through `rzpipe` | Portable CLI analysis, disassembly/debugging, many architectures and file formats, JSON command output | Good candidate for a process-backed Linux provider and fast metadata fallback. License/component inventory must be preserved; command output needs version-pinned parsers and semantic conformance before evidence is trusted. | -| [LIEF](https://github.com/lief-project/LIEF) | Apache-2.0; C++, Python, and other bindings | Deterministic parsing and modification of ELF, PE, Mach-O, COFF, and related executable formats; headers, sections, symbols, relocations, and functions | Best near-term complement, not a decompiler replacement. It can cover format metadata and artifact evidence without a long-lived analysis process; function semantics, pseudocode, CFG, and cross-reference parity remain out of scope unless separately demonstrated. | -| [Binary Ninja](https://docs.binary.ninja/dev/index.html) | API/documentation components are MIT, while the analysis product is licensed by edition; commercial, Ultimate, or Headless license is required for headless automation | Python/Core/C++/Rust APIs, headless loading, IL layers, function analysis, plugins, and configurable analysis | Strong technical fit for a native provider, especially function dossiers. Commercial licensing, license-secret handling, native runtime packaging, and multithreaded lifecycle rules are material deployment blockers. | - -## Recommended order - -1. Use the implemented explicit provider registry and target binding without - changing Hopper behavior. -2. Maintain the admitted Ghidra function boundary through the shared - conformance corpus and add formats or semantics only after real proof. -3. Connect Electron/native-add-on application findings to the selected native - analysis provider without introducing provider-prefixed tools. -4. Evaluate LIEF or Rizin later as complementary metadata/disassembly providers, - and Binary Ninja as an optional licensed provider, using the same admission - gate. - -## Required admission gate - -Before implementation, an adapter proposal must provide: - -- a capability matrix covering supported, unsupported, and degraded results; -- provider identity, version, analysis profile, target digest, authority, - limitations, and deterministic locations in every Evidence record; -- bounded subprocess or library lifetime, cancellation, timeouts, and cleanup; -- actionable local diagnostics that retain paths, digests, mismatch locations, - and provider metadata while redacting credentials, authorization headers, - license secrets, and other genuine secrets; -- the same source-owned fixture corpus across architectures and formats; -- repeatable checks for function identity, addresses, strings, names, xrefs, - CFG, and pseudocode wherever those capabilities are claimed. - -These gates turn the accepted direction into verified capabilities rather than -prematurely claiming equivalence or redistribution support. - -## Primary-source notes - -- Ghidra 12.1.4 documents headless batch mode and its Java runtime requirements - in its [release-specific Getting Started guide](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.1.4_build/GhidraDocs/GettingStarted.md); - the [official release](https://github.com/NationalSecurityAgency/ghidra/releases/tag/Ghidra_12.1.4_build) - supplies the corresponding distribution and checksums. -- Rizin lists supported formats, architectures, tools, and `rzpipe` bridges in - its [repository README](https://github.com/rizinorg/rizin); `rz-pipe` documents - JSON command transport and pipe backends. -- LIEF's [format tutorial](https://lief.re/doc/stable/tutorials/01_play_with_formats.html) - and [Python API](https://lief.re/doc/latest/api/binary_abstraction/python.html) - document parsing and format-agnostic binary access. -- Binary Ninja documents its [headless automation model](https://docs.binary.ninja/dev/batch.html), - [edition licenses](https://docs.binary.ninja/about/license.html), and the - [MIT license for API/documentation components](https://docs.binary.ninja/about/open-source.html). diff --git a/docs/roadmap.md b/docs/roadmap.md index 0df3a67c0..75d9f4679 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,125 +1,35 @@ # REA roadmap -## Tool direction +The [platform tracker](https://github.com/morluto/rea/issues/32), +[process/Hopper tracker](https://github.com/morluto/rea/issues/48), and +[browser tracker](https://github.com/morluto/rea/issues/39) track capability and +verification work. Available tools and setup are documented in the +[investigation guides](https://rea.tools/guides/), +[installation guide](installation.md), and +[generated catalog](mcp-contracts.md#generated-catalog). -REA provides inspection, capture, and comparison tools that return evidence -directly. Agents choose commands, paths, browser actions, scripts, and local -fixture servers, then compose experiments from those results. CLI and MCP must -expose equivalent behavior and preserve observations, inferences, and unknowns. +## Priorities -[#555](https://github.com/morluto/rea/pull/555) removed REA permission grants, -scope ceilings, elicitation, and repeated approval fields. -[#572](https://github.com/morluto/rea/pull/572) removed the replay engines, -Node characterization prepare/execute flow, and plan-only managed runtime -correlation tool. Those systems are retired roadmap items. Existing evidence -authority labels remain readable as provenance; they do not imply a current -replay executor. +- Expand native architecture, type, and indirect-call verification. +- Connect static findings and runtime observations across application layers. +- Improve obfuscated managed-code comparisons and verified native links. +- Extend process, protocol, filesystem, reconnect, and build-comparison coverage. +- Evaluate additional providers and targets when an analyst workflow demonstrates + a capability gap. -Local operations use the current user's OS permissions. Input and protocol -validation, provider prerequisites, target identity, cancellation, and owned -resource cleanup remain part of each tool's contract. Setup still discloses -installation changes and requires approval before writing or installing. +## Admission criteria -## Planned work +New capabilities must return useful evidence through shared CLI/MCP workflows, +preserve observations and unknowns, and declare actual authority and lifecycle +constraints. Agents compose experiments using ordinary commands, scripts, and +fixture servers; custom orchestration needs a demonstrated requirement. -The [website guides](https://rea.tools/guides/) and -[generated catalog](product-catalog.json) describe available workflows. -Current development priorities are: +Provider and platform claims require their corresponding +[real verification lanes](testing.md#real-toolchain-verification-lanes). +See [tool design](tool-design.md) for choosing a tool boundary and +[Ghidra semantics](ghidra-provider.md) for the existing deep-provider contract. -- Keep generated metadata and narrative documentation aligned with tools, - providers, setup options and releases. -- Expand native architecture, type and indirect-call verification across - Hopper and Ghidra. -- Connect additional static extractors and runtime observations to - cross-layer feature traces. -- Improve obfuscated .NET comparisons and links between managed findings - and verified native analysis. -- Extend process, protocol, filesystem, reconnect and build-comparison - coverage, plus browser and Electron scenario actions. -- Evaluate native runtime observation through LLDB, Frida, system logs and - API tracing, and additional tools and targets such as Binary Ninja, Rizin, - LIEF, Windows-native workflows, mobile applications and firmware. - -Provider additions and platform support require the corresponding real -verification lanes; see [testing](testing.md) and -[provider evaluation](provider-evaluation.md). - -## Remaining evidence and provider work - -The [platform roadmap](https://github.com/morluto/rea/issues/32), -[process and Hopper fidelity tracker](https://github.com/morluto/rea/issues/48), -and [browser tracker](https://github.com/morluto/rea/issues/39) track remaining -capabilities and proof. Their scope follows direct tools and agent-composed -experiments; custom replay languages and grant systems are not completion gates. - -[Inline Evidence composition](https://github.com/morluto/rea/pull/585) now returns -the complete record accepted by comparison tools. Managed inspection uses an -explicit PE/CLI target independently of the native provider selection. Comparisons -preserve unknowns when observation is incomplete, and PTY diagnostics retain the -actual loader or startup failure. Browser cleanup reports incomplete teardown -alongside the primary failure; transient documents invalidate only the affected -frame's WebMCP registrations. Real-provider and platform claims still require -their corresponding verification lanes. - -## Shipped behavior - -REA setup lets you select agent integration and optional Hopper installation. -It installs the bundled workflow, configures detected agents, and can save -verified paths for an existing Ghidra installation. It configures Claude Code, -Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity, -GitHub Copilot CLI, Command Code, VS Code, Grok Build, and OMP using each client's configuration format. Grok Bot is detected locally, but its connector is added from the Grok Bot chat because the signed-in account store is not a data-directory file. - -Ghidra analysis supports Linux x64/arm64 and macOS x64/arm64 with Ghidra 12.1.x and the -64-bit full JDK that installation declares. Current 12.1 releases require JDK 21 -or newer and set no maximum; the bridge is verified with Ghidra 12.1.4 and JDK 21. -Each installation requires the matching native decompiler. The -adapter exposes thirteen inventory operations and twelve function-analysis -operations, for 25 read-only operations total. Linux and macOS additionally support -atomic function-name and entry-comment edits with refreshed analysis; metadata -is discarded on close and executable bytes stay unchanged. Approved setup saves verified -installation paths in agent configurations without installing or changing -Ghidra or Java. - -Real-provider verification uses host-native debug and stripped fixtures plus -a native type-layout object. A separate lane covers AArch64 ELF, PE, and -Mach-O cross-target fixtures. See [testing](testing.md) for the prerequisites -and exact commands. - -Experimental Windows x64 P0 now supplies bundled Job Object ownership, -protected runtime DACLs, and handle-based admission for native x86 and x86-64 PE -applications on local NTFS. Real ordinary-user CLI/MCP verification covers -all 25 read-only operations and cleanup. The [Windows P0 guide](windows-ghidra-p0.md) -describes this boundary and unverified broader coverage. - -## Ghidra maintenance boundary - -Extend formats or semantics only with normalized provider-neutral contracts and -real source-owned conformance. Hopper and Ghidra pseudocode or assembly text is -not expected to match; unresolved targetless flow remains unknown. Automatic -Ghidra acquisition, if ever added, remains a separately planned and approved -related-tool change; setup must never install Java. - -Maintain Windows P0 with independent DACL readback, handle-based admission, -private authenticated IPC, and Job Object assignment before provider execution. -Process capture, Hopper, and broad filesystem-sensitive workflows remain -separate Windows projects; P0 does not imply their parity. - -## Capability-selective setup - -Setup already lets users select agent integration and Hopper installation. -Once REA supports installing additional analysis tools, it can expand these -choices to match the work a user wants to do. It may ask whether the operator wants to investigate -native binaries, websites, mobile applications, firmware, or runtime protocols, -then propose only the tools needed for the selected work. - -That future installer must preserve the current safety boundary: - -- detect and reuse existing tools; -- disclose every source, destination, license, command, and system effect; -- prefer user-local installation; -- install only explicitly selected toolchains; -- require tool-specific authorization for unattended system changes; -- verify each installed tool before reporting readiness. - -No placeholder tool choices or speculative installer registry are implemented -until another supported toolchain makes the abstraction concrete. +Setup remains additive, reuses existing tools, and requires approval for disclosed +configuration and Hopper installation changes. Additional installer choices need +an implemented toolchain and explicit scope; setup does not install or upgrade +unrelated runtimes or dependencies. From 077d6c407b3ea7443a7277ae0e5531b3927dd742 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:41:52 +0800 Subject: [PATCH 106/189] docs: correct MCP error and capture import guidance --- docs/migration-6.2.md | 2 +- docs/process-capture.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/migration-6.2.md b/docs/migration-6.2.md index 38baae073..8955f39f7 100644 --- a/docs/migration-6.2.md +++ b/docs/migration-6.2.md @@ -31,7 +31,7 @@ and carry their typed JSON diagnostic in a text content block; they omit if (reply.isError === true) { const text = reply.content.find((part) => part.type === "text"); if (text === undefined) throw new Error("REA error has no text diagnostic"); - const diagnostic = JSON.parse(text.text); + const { error: diagnostic } = JSON.parse(text.text); // Handle diagnostic.code, diagnostic.message and diagnostic.details. } ``` diff --git a/docs/process-capture.md b/docs/process-capture.md index 316d36c99..21f1f5343 100644 --- a/docs/process-capture.md +++ b/docs/process-capture.md @@ -157,8 +157,9 @@ results for unaffected dimensions and mark affected dimensions unknown; an incomplete capture cannot locate the first divergence across all dimensions. Trace assertions use coverage for the sources they select, so an assertion about complete raw terminal output need not fail because rendered snapshots -were omitted. Older truncated captures without these details retain the -conservative comparison behavior. These diagnostics use the existing scenario +were omitted. Captures missing `truncation_details` are rejected on import; +preserve them as historical files and recapture for current comparisons. +These diagnostics use the existing scenario budgets; they do not introduce a separate file-hashing budget. When the host withholds an unrelated process’s ownership token, REA leaves that From 392f1f310733f2c365da7bc57a1154cf10ec4ba0 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:56:01 +0800 Subject: [PATCH 107/189] refactor: consolidate boundary semantics and prune redundant tests Share parser modes and collision-free composite keys, enforce architecture guards, and consolidate redundant unit assertions into filesystem, CLI, MCP, and producer-backed workflows. Preserve concurrent upstream boundary fixes and exclude legacy Objective-C class-name bookkeeping labels. Validation: source/composition suites (3358 passing), focused canonical digest and MCP checks, typecheck/lint, Knip, formatting, architecture guards, and real Foundation archive and Apple legacy simulator CLI/MCP verification. No real Hopper, Ghidra, or IDA verification claim. --- .github/workflows/ci.yml | 3 +- package.json | 4 +- scripts/verify/apple/keyed-archive.mjs | 21 +- scripts/verify/apple/legacy-simulator.mjs | 142 +++++++++++++ scripts/verify/architecture-guards.mjs | 136 +++++++++++++ src/application/LinuxHopper.test.ts | 57 ++---- src/application/MacHopper.test.ts | 18 +- src/application/Setup.initialSnapshot.test.ts | 22 -- .../javascript/ElectronBoundaryGraphNative.ts | 5 +- ...JavaScriptApplicationEmptyLiterals.test.ts | 65 ++++-- .../JavaScriptModuleSpecifierPaths.test.ts | 161 ++++++++------- .../ManagedReconstructionService.test.ts | 69 ------- .../native/NativeApiInspection.test.ts | 25 --- .../apple/KeyedArchiveReader.test.ts | 35 ---- src/browser/CdpWebMcpDiscovery.ts | 8 +- src/browser/WebSourceMapFetcher.ts | 21 +- src/cliJsonInputStatus.test.ts | 95 --------- src/cliLogging.test.ts | 65 ++---- src/cliReferenceSourceImportStatus.test.ts | 126 ------------ src/contracts/sessionPathInputs.test.ts | 6 - src/contracts/workflowInputContracts.test.ts | 10 - src/domain/analysisProfile.test.ts | 15 -- src/domain/apple/plistValue.test.ts | 28 +-- src/domain/artifactIdentity.test.ts | 191 ------------------ src/domain/browserNetworkEvidence.test.ts | 26 --- src/domain/browserObservation.test.ts | 77 ------- src/domain/canonicalDigest.test.ts | 29 ++- src/domain/canonicalDigest.ts | 8 +- src/domain/changedBehavior.ts | 11 +- src/domain/digests.test.ts | 61 ------ src/domain/digests.ts | 5 - src/domain/dosCom.test.ts | 18 -- src/domain/evm/evmInterface.test.ts | 5 - src/domain/functionComparison.test.ts | 2 +- .../javascript/electronStaticAnalysisIpc.ts | 10 +- .../electronStaticAnalysisNative.ts | 9 +- .../javascriptApplicationVersionKeys.ts | 7 +- ...avascriptFeatureSeed.array_members.test.ts | 183 +++++++++-------- .../javascript/javascriptRecovery.test.ts | 21 -- .../javascriptSemanticCallResolution.ts | 2 + .../javascriptSemanticQuerySchemas.test.ts | 13 -- .../javascript/javascriptSemanticTraversal.ts | 6 +- .../javascript/javascriptSourceParser.ts | 54 +++-- .../javascriptStaticAnalysisHelpers.ts | 17 +- .../javascriptStaticPathResolution.test.ts | 15 -- .../javascript/sourceToBundleSignals.ts | 17 +- src/domain/jsonShape.test.ts | 71 ++----- src/domain/native/objcSwiftMetadata.ts | 11 +- src/domain/propertyListKeys.test.ts | 9 +- src/domain/reconstructionCoverage.ts | 11 +- src/domain/reconstructionUnknowns.ts | 16 +- .../referenceSourceImportParsing.test.ts | 81 -------- src/domain/referenceSourceImportParsing.ts | 23 +-- .../referenceSourceImportRecovery.test.ts | 150 -------------- .../referenceSourceRequireMembers.test.ts | 104 ---------- src/domain/residualUnknown.ts | 14 +- src/domain/safeJson.test.ts | 11 - src/domain/symbolAnalysis.test.ts | 183 +---------------- src/domain/symbolAnalysis.ts | 3 +- src/domain/unicodeCodePointOrder.ts | 8 + src/domain/webBundleAnalyzerInspection.ts | 10 +- src/domain/webInventory.test.ts | 25 +-- src/domain/webRuntime.test.ts | 37 ---- src/domain/webScreenshot.test.ts | 40 ---- src/ghidra/GhidraLauncherEnvironment.test.ts | 12 -- src/ghidra/GhidraSessionRoot.test.ts | 18 -- tests/boundary/cli/nativePlistCli.test.ts | 14 +- .../boundary/filesystem/dosComTarget.test.ts | 18 ++ .../referenceSourceComputedRequire.test.ts | 62 +++++- .../referenceSourceDynamicImports.test.ts | 11 +- .../referenceSourceRecovery.test.ts | 81 ++++++-- ...4-uses-complete-inventories-inline.test.ts | 90 ++++++--- .../mcp/enhancedTools.swiftTypes.test.ts | 13 +- tests/boundary/mcp/ghidraNativeApiMcp.test.ts | 5 + tests/boundary/mcp/managedMcp.test.ts | 20 +- .../native/keyed-archive-uid-root.swift | 3 +- .../javascriptArtifactTypeScriptDialect.ts | 5 + .../process-global/updateMaintenance.test.ts | 2 + 78 files changed, 1065 insertions(+), 2020 deletions(-) create mode 100644 scripts/verify/apple/legacy-simulator.mjs create mode 100644 scripts/verify/architecture-guards.mjs delete mode 100644 src/cliJsonInputStatus.test.ts delete mode 100644 src/cliReferenceSourceImportStatus.test.ts delete mode 100644 src/domain/artifactIdentity.test.ts delete mode 100644 src/domain/digests.test.ts delete mode 100644 src/domain/dosCom.test.ts delete mode 100644 src/domain/javascript/javascriptRecovery.test.ts delete mode 100644 src/domain/javascript/javascriptSemanticQuerySchemas.test.ts delete mode 100644 src/domain/referenceSourceImportParsing.test.ts delete mode 100644 src/domain/referenceSourceImportRecovery.test.ts delete mode 100644 src/domain/referenceSourceRequireMembers.test.ts delete mode 100644 src/domain/safeJson.test.ts delete mode 100644 src/domain/webRuntime.test.ts delete mode 100644 src/domain/webScreenshot.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d03dc87e..6755bb04c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -330,6 +330,8 @@ jobs: - run: npm run verify:keyed-archive - run: npm run verify:asset-catalog - run: npm run verify:macos-bundle + - name: Legacy simulator platform verification + run: npm run verify:legacy-simulator - name: Native installer and compiled NIB hierarchy regressions run: npm run test:focused -- tests/boundary/filesystem/installScript.test.ts tests/boundary/filesystem/nibNativeHierarchy.test.ts tests/boundary/filesystem/interfaceBuilderBundle.test.ts - name: Real binary metadata and Interface Builder integration @@ -423,7 +425,6 @@ jobs: tests/acceptance/webModuleCli.test.ts tests/acceptance/webSourceLocationCli.test.ts tests/boundary/cli/referenceSourceImportStatus.test.ts - src/cliReferenceSourceImportStatus.test.ts tests/boundary/filesystem/asarInventoryFreshness.test.ts tests/composition/javascript-applications/javascriptArtifactReconstruction.test.ts tests/conformance/providers/ghidra/windowsCapabilities.test.ts diff --git a/package.json b/package.json index a3d3bb0e1..abb5c215e 100644 --- a/package.json +++ b/package.json @@ -88,7 +88,7 @@ "prebuild": "npm run deps:check", "build": "node scripts/run-exclusive.mjs artifacts turbo run artifacts:skills --force", "precheck": "npm run deps:check", - "check": "node scripts/run-exclusive.mjs artifacts turbo run typecheck lint format:check knip metadata:check", + "check": "node scripts/run-exclusive.mjs artifacts turbo run typecheck lint format:check knip metadata:check && npm run verify:architecture-guards", "precheck:fast": "npm run deps:check", "check:fast": "turbo run typecheck lint --output-logs=errors-only", "precheck:changed": "npm run deps:check", @@ -144,6 +144,8 @@ "verify:native-ui": "npm run build:cached && node scripts/verify-native-ui.mjs", "verify:keyed-archive": "npm run build:cached && node scripts/verify/apple/keyed-archive.mjs", "verify:macos-bundle": "npm run build:cached && node scripts/verify/apple/macos-bundle.mjs", + "verify:legacy-simulator": "npm run build:cached && node scripts/verify/apple/legacy-simulator.mjs", + "verify:architecture-guards": "node scripts/verify/architecture-guards.mjs", "verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs", "verify:ghidra:swift": "npm run build:cached && node scripts/verify-real-ghidra-swift.mjs", "verify:ida": "npm run build:cached && node scripts/verify-real-ida.mjs", diff --git a/scripts/verify/apple/keyed-archive.mjs b/scripts/verify/apple/keyed-archive.mjs index d8bc284ba..f50eaacd1 100644 --- a/scripts/verify/apple/keyed-archive.mjs +++ b/scripts/verify/apple/keyed-archive.mjs @@ -148,8 +148,27 @@ try { target, status, })), - [{ source: null, path: ["UID"], target: 1, status: "resolved" }], + [ + { source: null, path: ["CF$UID"], target: 1, status: "resolved" }, + { source: null, path: ["UID"], target: 1, status: "resolved" }, + ], ); + const selected = await artifactCli("inspect-keyed-archive", path, [ + "--root", + "UID", + ]); + assert.deepEqual( + selected.references, + uidGraph.references.filter(({ path }) => path[0] === "UID"), + ); + await withArtifactMcp(path, async (client) => { + assert.deepEqual( + await artifactMcpResult(client, "inspect_keyed_archive", { + root: "UID", + }), + selected, + ); + }); } const numericTests = spawnSync( "npm", diff --git a/scripts/verify/apple/legacy-simulator.mjs b/scripts/verify/apple/legacy-simulator.mjs new file mode 100644 index 000000000..6ccc10ae2 --- /dev/null +++ b/scripts/verify/apple/legacy-simulator.mjs @@ -0,0 +1,142 @@ +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +import { + artifactCliEvidence, + artifactMcpResult, + withArtifactMcp, +} from "../../lib/artifact-e2e.mjs"; + +const exec = promisify(execFile); + +if (process.platform !== "darwin") + throw new Error( + "Legacy simulator verification requires a macOS host with full Xcode.", + ); +for (const tool of ["clang", "ld", "vtool", "otool"]) + await exec("/usr/bin/xcrun", ["--find", tool], { timeout: 30_000 }); +const { stdout: sdk } = await exec( + "/usr/bin/xcrun", + ["--sdk", "iphonesimulator", "--show-sdk-path"], + { timeout: 30_000 }, +); +const sdkPath = sdk.trim(); +assert.ok(sdkPath.length > 0, "iPhoneSimulator SDK path is empty"); + +const root = await mkdtemp(join(tmpdir(), "rea-legacy-simulator-")); +const xcrun = (...args) => + exec("/usr/bin/xcrun", args, { + timeout: 120_000, + maxBuffer: 16 * 1024 * 1024, + }); +try { + // Source-owned fixture, never executed: a legacy deployment target makes + // the Apple driver emit LC_VERSION_MIN_IPHONEOS (no simulator flag), while + // the modern dylib carries LC_BUILD_VERSION with an explicit simulator ID. + await writeFile(join(root, "library.c"), "int fixture(void) { return 7; }\n"); + await writeFile( + join(root, "main.c"), + "extern int fixture(void);\nint main(void) { return fixture(); }\n", + ); + for (const [source, deployment] of [ + ["library", "14.0"], + ["main", "9.0"], + ]) { + await xcrun( + "clang", + "-target", + `x86_64-apple-ios${deployment}-simulator`, + "-isysroot", + sdkPath, + "-c", + join(root, `${source}.c`), + "-o", + join(root, `${source}.o`), + ); + } + const common = ["-arch", "x86_64", "-syslibroot", sdkPath, "-lSystem"]; + await xcrun( + "ld", + ...common, + "-dylib", + "-platform_version", + "ios-simulator", + "14.0", + "14.0", + "-install_name", + "@rpath/libFixture.dylib", + join(root, "library.o"), + "-o", + join(root, "libFixture.dylib"), + ); + await xcrun( + "clang", + "-target", + "x86_64-apple-ios9.0-simulator", + "-isysroot", + sdkPath, + "-e", + "_main", + "-rpath", + "@loader_path", + join(root, "main.o"), + join(root, "libFixture.dylib"), + "-o", + join(root, "Main"), + ); + + // Apple oracle: the executable really uses the legacy command, the dylib + // really declares the modern simulator platform. + const { stdout: legacyBuild } = await xcrun( + "vtool", + "-show-build", + join(root, "Main"), + ); + assert.match(legacyBuild, /LC_VERSION_MIN_IPHONEOS/u); + assert.doesNotMatch(legacyBuild, /LC_BUILD_VERSION/u); + const { stdout: modernBuild } = await xcrun( + "vtool", + "-show-build", + join(root, "libFixture.dylib"), + ); + assert.match(modernBuild, /IOSSIMULATOR/u); + + // Real CLI over the fixture: the target is the executable file (plain + // directories are not binary targets); @loader_path resolves against its + // directory. The legacy x86 image must classify as iOS simulator + // (platform 7) and resolve against the modern dylib. + // The fixture is inspected, never executed or loaded into this process. + const mainPath = join(root, "Main"); + const trace = (await artifactCliEvidence("trace-dylib-resolution", mainPath)) + .normalized_result; + const main = trace.images.find(({ path }) => path === "Main"); + assert.ok(main, "trace omitted the Main image"); + assert.equal(main.parse_status, "parsed"); + assert.deepEqual(main.slices[0]?.platforms, [7]); + const edge = trace.edges.find( + ({ loader, install_name: name }) => + loader === "Main" && name === "@rpath/libFixture.dylib", + ); + assert.ok(edge, "trace omitted the @rpath edge"); + assert.deepEqual(edge.resolution, { + status: "resolved", + image: "libFixture.dylib", + }); + + await withArtifactMcp(mainPath, async (client) => { + assert.deepEqual( + await artifactMcpResult(client, "trace_dylib_resolution"), + trace, + ); + }); + console.log( + "Legacy simulator verification passed against Apple clang, ld, vtool, and otool.", + ); +} finally { + await rm(root, { recursive: true, force: true }); +} diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs new file mode 100644 index 000000000..efe2a8df4 --- /dev/null +++ b/scripts/verify/architecture-guards.mjs @@ -0,0 +1,136 @@ +import assert from "node:assert/strict"; +import { readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; + +// Architecture guards for the strict-identity / best-effort-inference split. +// - Evidence ordering must be locale-independent (ICU varies by host), so +// src/domain orders with compareUnicodeCodePoints, never localeCompare. +// - Composite dedup keys must not NUL-join variable-length or free-form +// MIDDLE fields: ["a\0b"] collapses with ["a", "b"] and drops a finding. +// compositeKey (JSON tuple) is the single owner for composite keys. +// - Transparent wrappers unwrap in exactly one place +// (javascriptAstValues.unwrapJavaScriptExpression); direct isTS* unwrapping +// elsewhere drifts (the `satisfies` class of bug). +// - AST walks go through traverseJavaScriptAst/childNodes: bespoke +// Object.values walkers diverge on loc/comment fields and overflow the +// stack on deep generated chains. + +const root = new URL("../../", import.meta.url).pathname; + +const listFiles = async (dir) => { + const output = []; + for (const entry of await readdir(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) output.push(...(await listFiles(path))); + else if ( + entry.name.endsWith(".ts") && + !entry.name.endsWith(".test.ts") && + !entry.name.endsWith(".fixture.ts") + ) + output.push(path); + } + return output; +}; + +const stripComments = (content) => + content + .split("\n") + .filter((line) => !line.trimStart().startsWith("//")) + .join("\n") + .replace(/\/\*[\s\S]*?\*\//gu, ""); + +const sources = await listFiles(join(root, "src")); +const files = await Promise.all( + sources.map(async (path) => ({ + path: path.slice(root.length), + content: stripComments(await readFile(path, "utf8")), + })), +); +const inDir = (dir) => files.filter((file) => file.path.startsWith(dir)); + +const failures = []; +const check = (label, selected, pattern, allow = []) => { + const offenders = selected.filter( + (file) => pattern.test(file.content) && !allow.includes(file.path), + ); + if (offenders.length > 0) + failures.push( + `${label}:\n${offenders.map((file) => ` ${file.path}`).join("\n")}`, + ); +}; + +check( + "src/domain uses localeCompare (use compareUnicodeCodePoints)", + inDir("src/domain/"), + /\.localeCompare\(/, +); + +check( + "NUL-joined list key (use compositeKey)", + files, + /\.join\(["']\\0["']\)/, + [ + // Sorted pair of constrained trace IDs; documented in plan. + "src/domain/process/processTraceSpecification.ts", + ], +); + +check( + "direct transparent-wrapper unwrap outside javascriptAstValues (use unwrapJavaScriptExpression)", + files, + /isTSAsExpression|isTSSatisfiesExpression|isTSNonNullExpression|isTSTypeAssertion|isTSInstantiationExpression|isParenthesizedExpression/, + ["src/domain/javascript/javascriptAstValues.ts"], +); + +check( + "bespoke AST child walker (use traverseJavaScriptAst/childNodes)", + files, + /VISITOR_KEYS/, + ["src/domain/javascript/javascriptSemanticTraversal.ts"], +); + +// Fixed-arity backtick keys audited 2026-10-10: every prefix field is NUL-free +// (hex digests, file paths, enums, numbers, or compositeKey JSON which escapes +// NUL), with free-form source strings only in final position. New backtick-\0 +// keys must either meet that shape (and extend this list with justification) +// or use compositeKey. +check( + "new backtick-NUL composite key (audit against the rule above)", + files, + /`[^`\n]*\\0/, + [ + "src/application/javascript/ElectronBoundaryAnalysis.ts", + "src/application/javascript/ElectronBoundaryGraphContext.ts", + "src/application/javascript/JavaScriptArtifactGraphContext.ts", + "src/browser/CdpCaptureCompleteness.ts", + "src/browser/CdpCaptureEventHandlers.ts", + "src/browser/CdpPageCapture.ts", + "src/browser/WebSourceMapFetcher.ts", + "src/domain/javascript/electronStaticAnalysisBrowser.ts", + "src/domain/javascript/electronStaticAnalysisIpc.ts", + "src/domain/javascript/javascriptApplicationChangeGraph.ts", + "src/domain/javascript/javascriptApplicationVersionItems.ts", + "src/domain/javascript/javascriptApplicationVersionKeys.ts", + "src/domain/javascript/javascriptExportShapeSelection.ts", + "src/domain/javascript/javascriptFeatureSeed.ts", + "src/domain/javascript/javascriptFeatureTraversal.ts", + "src/domain/javascript/javascriptNativeHandoff.ts", + "src/domain/javascript/javascriptRuntimeReconciliationMatching.ts", + "src/domain/javascript/javascriptRuntimeReconciliationSchemas.ts", + "src/domain/javascript/javascriptSemanticQuery.ts", + "src/domain/javascript/javascriptStaticAnalysisBundler.ts", + "src/domain/javascript/javascriptStaticAnalysisCalls.ts", + "src/domain/javascript/javascriptStaticAnalysisFindings.ts", + "src/domain/localPath.ts", + "src/domain/process/processTraceEvaluation.ts", + "src/domain/process/processTraceSpecification.ts", + "src/domain/unicodeCodePointOrder.ts", + "src/domain/webBundleAnalyzerInspection.ts", + ], +); + +if (failures.length > 0) { + console.error(`Architecture guards failed:\n\n${failures.join("\n\n")}\n`); + process.exit(1); +} +console.log(`Architecture guards passed across ${files.length} source files.`); diff --git a/src/application/LinuxHopper.test.ts b/src/application/LinuxHopper.test.ts index 4e622da6c..e3e0091b3 100644 --- a/src/application/LinuxHopper.test.ts +++ b/src/application/LinuxHopper.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest"; import { installLinuxHopper, linuxHopperLauncherDigestSupported, - linuxHopperInstallDisclosure, linuxPackageManagerCommands, linuxSharedLibrariesAvailable, parseLinuxDistribution, @@ -114,44 +113,11 @@ describe("Linux Hopper installation", () => { expect(linuxHopperLauncherDigestSupported("0".repeat(64))).toBe(false); }); - it("discloses the exact download, integrity evidence, and privileged command", () => { - expect(linuxHopperInstallDisclosure("deb", false)).toEqual({ - downloadUrl: - "https://www.hopperapp.com:443/downloader/public/Hopper-6.4.2-Linux-demo.deb", - expectedBytes: 35_755_772, - expectedSha1: "e4f79dff602648a8ff4a88b773875b6bfac0dc65", - commands: [ - "pkexec apt-get install -y xvfb xauth python3 libx11-6 libxtst6", - ], - }); - }); - it.each([ - ["deb", "apt-get"], - ["rpm", "dnf"], - ["arch", "pacman"], - ] as const)("selects the %s native package manager", (family, executable) => { - expect( - linuxPackageManagerCommands(family, "/tmp/Hopper package", true), - ).toContainEqual( - expect.objectContaining({ - executable, - }), - ); - expect( - linuxPackageManagerCommands(family, "/tmp/Hopper package", false), - ).toContainEqual( - expect.objectContaining({ - executable: "pkexec", - args: expect.arrayContaining([executable, "/tmp/Hopper package"]), - }), - ); - }); - - it.each([ - ["deb", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]], + ["deb", "apt-get", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]], [ "rpm", + "dnf", [ "xorg-x11-server-Xvfb", "xorg-x11-xauth", @@ -160,17 +126,30 @@ describe("Linux Hopper installation", () => { "libXtst", ], ], - ["arch", ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"]], + [ + "arch", + "pacman", + ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"], + ], ] as const)( - "installs the %s demo-session dependencies", - (family, packages) => { + "selects the %s native package manager and dependencies", + (family, executable, packages) => { expect( linuxPackageManagerCommands(family, "/tmp/Hopper package", true), ).toContainEqual( expect.objectContaining({ + executable, args: expect.arrayContaining([...packages]), }), ); + expect( + linuxPackageManagerCommands(family, "/tmp/Hopper package", false), + ).toContainEqual( + expect.objectContaining({ + executable: "pkexec", + args: expect.arrayContaining([executable, "/tmp/Hopper package"]), + }), + ); }, ); diff --git a/src/application/MacHopper.test.ts b/src/application/MacHopper.test.ts index 951560a27..d75959fd5 100644 --- a/src/application/MacHopper.test.ts +++ b/src/application/MacHopper.test.ts @@ -2,11 +2,7 @@ import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; -import { - installMacHopper, - macHopperInstallDisclosure, - type MacHopperInstallHost, -} from "./MacHopper.js"; +import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js"; class FakeMacHopperHost implements MacHopperInstallHost { readonly archive = new TextEncoder().encode("hopper-dmg"); @@ -75,18 +71,6 @@ class FakeMacHopperHost implements MacHopperInstallHost { } describe("macOS Hopper installation", () => { - it("discloses network and command boundaries before installation", () => { - expect(macHopperInstallDisclosure).toMatchObject({ - networkOrigins: [ - "https://www.hopperapp.com/include/files-api.php?request=releases&public=true", - "https://www.hopperapp.com:443/downloader/public/", - ], - }); - expect(macHopperInstallDisclosure.commands).toContain( - "hdiutil attach -readonly -nobrowse -mountpoint ", - ); - }); - it("installs, verifies, opens, and cleans the official package", async () => { const host = new FakeMacHopperHost(); await expect(installMacHopper({}, host)).resolves.toEqual({ diff --git a/src/application/Setup.initialSnapshot.test.ts b/src/application/Setup.initialSnapshot.test.ts index 06e9230c2..e281473dc 100644 --- a/src/application/Setup.initialSnapshot.test.ts +++ b/src/application/Setup.initialSnapshot.test.ts @@ -3,27 +3,6 @@ import { expect, it } from "vitest"; import { runSetup } from "./Setup.js"; import { FakeSetupHost, options } from "./Setup.fixture.js"; -it("uses the shared initial host snapshot for setup planning", async () => { - const host = new FakeSetupHost(); - host.initialSetupState = async (scope) => ({ - hopperPath: "/snapshot/Hopper", - providerEnvironment: { HOPPER_LAUNCHER_PATH: "/snapshot/Hopper" }, - doctor: await host.doctor(scope), - }); - host.clients = [{ name: "codex", configPath: "/codex.json" }]; - - const result = await runSetup( - { ...options(false), dryRun: true, clientIds: ["codex"] }, - host, - ); - - expect(result.status).toBe("planned"); - expect(result.plannedActions.map(({ id }) => id)).toContain( - "configure_client:codex", - ); - expect(host.doctorCalls).toBe(1); -}); - it("refreshes doctor after approved setup changes", async () => { const host = new FakeSetupHost(); host.doctorHealthy = false; @@ -41,5 +20,4 @@ it("refreshes doctor after approved setup changes", async () => { ); expect(result.doctor.healthy).toBe(true); - expect(host.doctorCalls).toBe(2); }); diff --git a/src/application/javascript/ElectronBoundaryGraphNative.ts b/src/application/javascript/ElectronBoundaryGraphNative.ts index fffb3f5fb..a140c9a2c 100644 --- a/src/application/javascript/ElectronBoundaryGraphNative.ts +++ b/src/application/javascript/ElectronBoundaryGraphNative.ts @@ -7,6 +7,7 @@ import { type JavaScriptArtifactGraphCoverage, } from "./JavaScriptArtifactGraphContext.js"; import { astObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js"; +import { compositeKey } from "../../domain/unicodeCodePointOrder.js"; import { addElectronInferenceEdge, electronFindingSourceNode, @@ -50,7 +51,9 @@ const addNativeBinding = (input: NativeBindingInput): void => { identity: electronObservationIdentity( context, "javascript-requested-native-export", - `${file.path}:${value.specifier}:${value.binding_kind}:${value.members.join("\0")}:${electronRangeKey(value.location)}`, + // Members are a variable-length source-derived list: compositeKey keeps + // ["a\0b"] distinct from ["a", "b"] inside the digested identity. + `${file.path}:${value.specifier}:${value.binding_kind}:${compositeKey(value.members)}:${electronRangeKey(value.location)}`, ), observations: [ { diff --git a/src/application/javascript/JavaScriptApplicationEmptyLiterals.test.ts b/src/application/javascript/JavaScriptApplicationEmptyLiterals.test.ts index b200b91ea..33ebd2220 100644 --- a/src/application/javascript/JavaScriptApplicationEmptyLiterals.test.ts +++ b/src/application/javascript/JavaScriptApplicationEmptyLiterals.test.ts @@ -31,28 +31,49 @@ const analyzeSource = async ( ); }; -it.each([ - "fetch('');", - "new WebSocket('');", - "navigator.serviceWorker.register('');", - "new Worker('');", - "const x = require('');", - "import y from ''; y();", - "import('');", - "localStorage.getItem('');", - "localStorage.setItem('', 1);", - "indexedDB.open('');", - "win.loadFile('');", - "win.loadURL('');", - "app.get('', handler);", - "process.on('', () => 1);", - "const { EventEmitter } = require('events'); new EventEmitter().on('', () => 1);", - "const { spawn } = require('child_process'); spawn('/bin/x').on('', () => 1);", - "const { ipcMain } = require('electron'); ipcMain.handle('', () => 1);", - "const { ipcRenderer } = require('electron'); ipcRenderer.invoke('');", - "const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {});", -])("analyzes the legal empty string literal in %s", async (source) => { - await expect(analyzeSource(source)).resolves.toBeDefined(); +it("retains empty literal evidence across the application boundary surfaces", async () => { + const sources = [ + "fetch('');", + "new WebSocket('');", + "navigator.serviceWorker.register('');", + "new Worker('');", + "const x = require('');", + "import y from ''; y();", + "import('');", + "localStorage.getItem('');", + "localStorage.setItem('', 1);", + "indexedDB.open('');", + "win.loadFile('');", + "win.loadURL('');", + "app.get('', handler);", + "process.on('', () => 1);", + "const { EventEmitter } = require('events'); new EventEmitter().on('', () => 1);", + "const { spawn } = require('child_process'); spawn('/bin/x').on('', () => 1);", + "const { ipcMain } = require('electron'); ipcMain.handle('', () => 1);", + "const { ipcRenderer } = require('electron'); ipcRenderer.invoke('');", + "const { contextBridge } = require('electron'); contextBridge.exposeInMainWorld('', {});", + ]; + const output = await analyzeSource(sources.join("\n")); + expect(output.graph.nodes).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "endpoint" }), + expect.objectContaining({ kind: "worker" }), + expect.objectContaining({ kind: "ipc-channel" }), + expect.objectContaining({ kind: "context-bridge-api" }), + ]), + ); + expect(output.semantic_graph?.nodes).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "request", + properties: expect.objectContaining({ endpoint: "" }), + }), + expect.objectContaining({ + kind: "event", + properties: expect.objectContaining({ event_name: "" }), + }), + ]), + ); }); it("analyzes a plain long-line loader without package metadata", async () => { diff --git a/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts b/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts index a31b2a2ca..74a69d1f9 100644 --- a/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts +++ b/src/application/javascript/JavaScriptModuleSpecifierPaths.test.ts @@ -159,21 +159,26 @@ describe("module specifier punctuation", () => { }); describe("ESM module URL decoding", () => { - it.each([ - ["./plain.mjs", "plain.mjs"], - ["./space%20name.mjs", "space name.mjs"], - ["./pr%C3%A9load.mjs", "préload.mjs"], - ["./name%3F%23.mjs", "name?#.mjs"], - ["./percent%2520.mjs?cache=1#v2", "percent%20.mjs"], - ])( - "points %s imports to the file loaded by Node", - async (specifier, target) => { - const root = await createTestTempDirectory("rea-module-url-"); - const main = join(root, "main.mjs"); - await writeFile( - main, - `import value from ${JSON.stringify(specifier)}; console.log(value);`, - ); + it("resolves URL-encoded imports to the files loaded by Node", async () => { + const cases = [ + ["./plain.mjs", "plain.mjs"], + ["./space%20name.mjs", "space name.mjs"], + ["./pr%C3%A9load.mjs", "préload.mjs"], + ["./name%3F%23.mjs", "name?#.mjs"], + ["./percent%2520.mjs?cache=1#v2", "percent%20.mjs"], + ] as const; + const root = await createTestTempDirectory("rea-module-url-"); + const main = join(root, "main.mjs"); + await writeFile( + main, + cases + .map( + ([specifier], index) => + `import value${index} from ${JSON.stringify(specifier)}; console.log(value${index});`, + ) + .join("\n"), + ); + for (const [specifier, target] of cases) { await writeFile( join(root, target), `export default ${JSON.stringify(target)};`, @@ -181,19 +186,23 @@ describe("ESM module URL decoding", () => { const encoded = specifier.slice(2).split("?", 1)[0]?.split("#", 1)[0]; if (encoded !== undefined && encoded !== target) await writeFile(join(root, encoded), 'export default "encoded decoy";'); - const native = await promisify(execFile)(process.execPath, [main], { - timeout: 5_000, - }); - expect(native.stdout.trim()).toBe(target); + } + const native = await promisify(execFile)(process.execPath, [main], { + timeout: 5_000, + }); + expect(native.stdout.trim().split("\n")).toEqual( + cases.map(([, target]) => target), + ); - const result = await analyzeJavaScriptApplication({ - input_path: root, - format: "directory", - }); - if (!result.ok) throw result.error; - const { graph } = javascriptApplicationAnalysisResultSchema.parse( - result.value.normalized_result, - ); + const result = await analyzeJavaScriptApplication({ + input_path: root, + format: "directory", + }); + if (!result.ok) throw result.error; + const { graph } = javascriptApplicationAnalysisResultSchema.parse( + result.value.normalized_result, + ); + for (const [specifier, target] of cases) { const imports = graph.edges.filter( (edge) => edge.relation === "imports" && @@ -202,8 +211,8 @@ describe("ESM module URL decoding", () => { expect(imports.length).toBeGreaterThan(0); for (const edge of imports) expect(edge.properties.resolved_path).toBe(target); - }, - ); + } + }); it("preserves CommonJS literal percent names", () => { expect( @@ -249,26 +258,21 @@ const packageEntryUrlCases = [ ["main", "./actual#file.cjs", "actual#file.cjs"], ] as const; -describe("package exports URL paths", () => { - it.each( - (["import", "require"] as const).flatMap((moduleKind) => - packageEntryUrlCases.map(([field, declaredPath, target]) => ({ - moduleKind, - field, - declaredPath, - target, - })), - ), - )( - "matches Node $moduleKind for $field $declaredPath", - async ({ moduleKind, field, declaredPath, target }) => { - const root = await createTestTempDirectory("rea-package-export-url-"); - const packageRoot = join(root, "node_modules", "fixture"); +it.each(["import", "require"] as const)( + "matches Node %s across package exports and main path representations", + async (moduleKind) => { + const root = await createTestTempDirectory("rea-package-export-url-"); + for (const [ + index, + [field, declaredPath, target], + ] of packageEntryUrlCases.entries()) { + const name = `fixture-${index}`; + const packageRoot = join(root, "node_modules", name); await mkdir(packageRoot, { recursive: true }); await writeFile( join(packageRoot, "package.json"), JSON.stringify({ - name: "fixture", + name, [field]: declaredPath, }), ); @@ -282,41 +286,54 @@ describe("package exports URL paths", () => { join(packageRoot, literal), 'module.exports="literal decoy";', ); - const main = join( - root, - moduleKind === "import" ? "main.mjs" : "main.cjs", - ); - await writeFile( - main, - moduleKind === "import" - ? 'import value from "fixture"; console.log(value);' - : 'console.log(require("fixture"));', - ); - const native = await promisify(execFile)(process.execPath, [main], { - timeout: 5_000, - }); - expect(native.stdout.trim()).toBe(target); - const result = await analyzeJavaScriptApplication({ - input_path: root, - format: "directory", - }); - if (!result.ok) throw result.error; - const { graph } = javascriptApplicationAnalysisResultSchema.parse( - result.value.normalized_result, - ); + } + const main = join(root, moduleKind === "import" ? "main.mjs" : "main.cjs"); + await writeFile( + main, + packageEntryUrlCases + .map((_, index) => + moduleKind === "import" + ? `import value${index} from "fixture-${index}"; console.log(value${index});` + : `console.log(require("fixture-${index}"));`, + ) + .join("\n"), + ); + const native = await promisify(execFile)(process.execPath, [main], { + timeout: 5_000, + }); + expect(native.stdout.trim().split("\n")).toEqual( + packageEntryUrlCases.map(([, , target]) => target), + ); + const result = await analyzeJavaScriptApplication({ + input_path: root, + format: "directory", + }); + if (!result.ok) throw result.error; + const { graph } = javascriptApplicationAnalysisResultSchema.parse( + result.value.normalized_result, + ); + for (const [ + index, + [field, declaredPath, target], + ] of packageEntryUrlCases.entries()) { const imports = graph.edges.filter( (edge) => edge.relation === "imports" && - edge.properties.specifier === "fixture", + edge.properties.specifier === `fixture-${index}`, ); - expect(imports.length).toBeGreaterThan(0); + expect( + imports.length, + `${moduleKind}: ${field} ${declaredPath}`, + ).toBeGreaterThan(0); for (const edge of imports) expect(edge.properties.resolved_path).toBe( - `node_modules/fixture/${target}`, + `node_modules/fixture-${index}/${target}`, ); - }, - ); + } + }, +); +describe("package exports URL path rejections", () => { it.each( (["import", "require"] as const).flatMap((moduleKind) => [ diff --git a/src/application/managed/ManagedReconstructionService.test.ts b/src/application/managed/ManagedReconstructionService.test.ts index 889672ce1..6e7a28c27 100644 --- a/src/application/managed/ManagedReconstructionService.test.ts +++ b/src/application/managed/ManagedReconstructionService.test.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { describe, expect, it } from "vitest"; import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../../contracts/managed/managedWorkflowExamples.js"; @@ -24,50 +22,6 @@ const exampleMethod = () => { }; describe("managed decompiler reconstruction import", () => { - it("imports decompiler output as inference locked to static IL evidence", () => { - const result = importManagedReconstruction(exampleInput()); - - expect(result).toMatchObject({ - phase: "reconstruction-import", - executed: false, - static_observation: { - artifact_sha256: "2".repeat(64), - mvid: "11112222-3333-4444-9555-666677778888", - }, - decompiler: { - name: "ilspycmd", - version: "9.1.0.7988", - family: "ilspy", - }, - summary: { - imported_methods: 1, - decompiled_csharp_methods: 1, - }, - methods: [ - { - token: "0x06000001", - signature_sha256: "3".repeat(64), - normalized_il_sha256: "5".repeat(64), - validation: { - matched_static_member: true, - exact_build_required: true, - canonical_observation: false, - confidence_floor: "inference", - }, - }, - ], - }); - expect(result.reconstruction_id).toMatch(/^mre_[a-f0-9]{64}$/u); - expect(result.methods[0]?.reconstruction.text_sha256).toBe( - createHash("sha256") - .update("internal static void Main() { }") - .digest("hex"), - ); - expect(result.limitations.join(" ")).toContain( - "metadata and IL observations remain canonical", - ); - }); - it("rejects reconstruction text hash drift", () => { expect(() => importManagedReconstruction({ @@ -147,29 +101,6 @@ describe("managed decompiler reconstruction import", () => { }), ).toThrow(/does not match/u); }); - - it("wraps imported reconstruction in Evidence", () => { - const evidence = importManagedReconstructionEvidence(exampleInput()); - - if (!evidence.ok) throw evidence.error; - expect(evidence.value).toMatchObject({ - operation: "import_managed_reconstruction", - provider: { id: "rea-dotnet-workflows" }, - confidence: "inferred", - authority: "analyst-inference", - normalized_result: { - phase: "reconstruction-import", - methods: [ - { - reconstruction: { - kind: "decompiled-csharp", - language: "csharp", - }, - }, - ], - }, - }); - }); }); describe("managed reconstruction input diagnostics", () => { diff --git a/src/application/native/NativeApiInspection.test.ts b/src/application/native/NativeApiInspection.test.ts index d3bd88b7b..999010638 100644 --- a/src/application/native/NativeApiInspection.test.ts +++ b/src/application/native/NativeApiInspection.test.ts @@ -71,31 +71,6 @@ describe("native API switch uncertainty", () => { }); describe("native API inspection", () => { - it("preserves structured type and jump-table boundary evidence", () => { - const dossier = functionDossierSchema.parse(ghidraFunctionDossier()); - - expect(projectNativeApiInspection(dossier)).toMatchObject({ - procedure: { address: "0x401000", name: "fixture_main" }, - boundary: { - available: true, - return_type: { data_type: "int", confidence: "medium" }, - jump_tables: [ - { - dispatch_address: "0x401010", - data_sources: [{ address: "0x403000" }], - mappings: [ - { - target_address: "0x401020", - }, - ], - }, - ], - }, - unsupported_branches: [], - residual_unknowns: [], - }); - }); - it("preserves unsupported provider branches as residual unknowns", () => { const value = ghidraFunctionDossier(); if (typeof value !== "object" || value === null || Array.isArray(value)) diff --git a/src/artifacts/apple/KeyedArchiveReader.test.ts b/src/artifacts/apple/KeyedArchiveReader.test.ts index 3910eef5c..dd569a6e5 100644 --- a/src/artifacts/apple/KeyedArchiveReader.test.ts +++ b/src/artifacts/apple/KeyedArchiveReader.test.ts @@ -51,41 +51,6 @@ describe("inert keyed archive decoding", () => { expect.objectContaining({ source: 1, target: 2, status: "resolved" }), ); }); - it.each([ - ["binary", { UID: 1 }], - ["XML", { CF$UID: 1 }], - ] as const)( - "resolves a %s root encoded under a UID-named key", - (format, reference) => { - const named = { - ...archive, - $objects: ["$null", "payload"], - $top: { UID: reference, CF$UID: reference }, - }; - const graph = decodeKeyedArchiveBytes( - Buffer.from(format === "binary" ? buildBinary(named) : build(named)), - { offset: 0, limit: 2 }, - ); - expect( - graph.references.map(({ source, path, target, status }) => ({ - source, - path, - target, - status, - })), - ).toEqual([ - { source: null, path: ["CF$UID"], target: 1, status: "resolved" }, - { source: null, path: ["UID"], target: 1, status: "resolved" }, - ]); - const selected = decodeKeyedArchiveBytes( - Buffer.from(format === "binary" ? buildBinary(named) : build(named)), - { root: "UID", offset: 0, limit: 2 }, - ); - expect(selected.references).toEqual([ - expect.objectContaining({ path: ["UID"], target: 1 }), - ]); - }, - ); it("reports an XML archive dictionary keyed __proto__ as omitted", () => { const xml = build({ ...archive, $objects: ["$null", "value"] }).replace( "$top", diff --git a/src/browser/CdpWebMcpDiscovery.ts b/src/browser/CdpWebMcpDiscovery.ts index ae805b19c..240043f08 100644 --- a/src/browser/CdpWebMcpDiscovery.ts +++ b/src/browser/CdpWebMcpDiscovery.ts @@ -6,6 +6,7 @@ import type { WebMcpDiscovery, } from "../domain/webMcpDiscovery.js"; import { inferJsonShape } from "../domain/jsonShape.js"; +import { compositeKey } from "../domain/unicodeCodePointOrder.js"; import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js"; import type { CdpConnection, CdpEvent } from "./CdpConnection.js"; import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js"; @@ -502,8 +503,11 @@ const buildWebMcpResult = (options: WebMcpResultOptions): WebMcpDiscovery => { const toolKey = (frameUrl: string, frameId: string, name: string): string => // Registrations without a known admitted frame are excluded above, so the - // frame ID here always distinguishes owners and keys cannot collapse. - `webmcp_${createHash("sha256").update(`${frameUrl}\0${frameId}\0${name}`).digest("hex")}`; + // frame ID here always distinguishes owners. Composite tuple keeps a NUL + // inside one field from collapsing two registrations before hashing. + `webmcp_${createHash("sha256") + .update(compositeKey([frameUrl, frameId, name])) + .digest("hex")}`; const booleanOrNull = (value: unknown): boolean | null => typeof value === "boolean" ? value : null; diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index 3c2d3ae81..9a16e5d41 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -268,6 +268,20 @@ const fetchOne = async ( } }; +/** + * Fetch redirect statuses per WHATWG Fetch (redirect status list: + * 301, 302, 303, 307, 308). Single owner for redirect decisions. + * 300/304/305/306 carry `Location` without being redirects — following + * them would replace the observed failure with an unrelated map. + * See https://fetch.spec.whatwg.org/#redirect-status + */ +export const isFetchRedirectStatus = (status: number): boolean => + status === 301 || + status === 302 || + status === 303 || + status === 307 || + status === 308; + const fetchFollowingApprovedRedirects = async ( initialUrl: string, allowedOrigins: readonly string[], @@ -298,9 +312,10 @@ const fetchFollowingApprovedRedirects = async ( await response.body?.cancel(signal.reason).catch(() => undefined); throw signal.reason; } - // Location is a redirect target only for the Fetch redirect statuses. - // A 304 or another 3xx response must retain its own HTTP failure. - if (![301, 302, 303, 307, 308].includes(response.status)) + // `Location` is a redirect target only for Fetch redirect statuses. + // Other 3xx responses retain their own HTTP failure (strict identity: + // never replace the observed failure with an unrelated map). + if (!isFetchRedirectStatus(response.status)) return { response, fetchedUrl: current }; const location = response.headers.get("location"); if (location === null) return { response, fetchedUrl: current }; diff --git a/src/cliJsonInputStatus.test.ts b/src/cliJsonInputStatus.test.ts deleted file mode 100644 index f4bf8854d..000000000 --- a/src/cliJsonInputStatus.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { isCliOperationFailure } from "./cliLogging.js"; -import { - analysisCliErrorEnvelopeSchema, - analysisErrorProjectionSchema, -} from "./contracts/errorSchemas.js"; -import { AnalysisInputError } from "./domain/analysisErrorCore.js"; -import { projectAnalysisError } from "./domain/analysisErrorProjection.js"; - -const projection = projectAnalysisError(new AnalysisInputError("test-input")); -const envelope = { error: "Application workflow failed", ...projection }; - -describe("CLI JSON input failure recognition", () => { - it.each([ - {}, - { input_path: "input.json" }, - { input_reason: "invalid-json" }, - { input_path: "input.json", input_reason: "invalid-json" }, - { input_path: "missing.json", input_reason: "read-failed" }, - { input_path: "large.json", input_reason: "too-large" }, - { input_path: "", input_reason: "read-failed" }, - ])("recognizes a complete envelope with metadata %j", (metadata) => { - const value = { ...envelope, ...metadata }; - expect(analysisCliErrorEnvelopeSchema.parse(value)).toEqual(value); - expect(isCliOperationFailure(value)).toBe(true); - }); - - it.each([ - { input_path: null }, - { input_path: 1 }, - { input_path: ["input.json"] }, - { input_reason: null }, - { input_reason: 1 }, - { input_reason: "" }, - { input_reason: "unknown" }, - { input_reason: ["invalid-json"] }, - { unknown_field: "extra" }, - { input_path: "input.json", input_reason: "invalid-json", extra: true }, - { error: "" }, - { error: 1 }, - { retryable: "false" }, - { remediation: { action: "retry", extra: true } }, - ])("rejects malformed or unknown envelope fields %j", (changes) => { - const value = { ...envelope, ...changes }; - expect(analysisCliErrorEnvelopeSchema.safeParse(value).success).toBe(false); - expect(isCliOperationFailure(value)).toBe(false); - }); - - it.each(["code", "category", "message", "retryable", "remediation"])( - "requires the complete canonical projection, including %s", - (field) => { - const value = Object.fromEntries( - Object.entries({ ...envelope, input_reason: "invalid-json" }).filter( - ([key]) => key !== field, - ), - ); - expect(analysisCliErrorEnvelopeSchema.safeParse(value).success).toBe( - false, - ); - expect(isCliOperationFailure(value)).toBe(false); - }, - ); - - it.each([ - { error: "ordinary data" }, - { code: "invalid_request", message: "ordinary data" }, - { - error: "ordinary data", - code: "invalid_request", - input_path: "input.json", - }, - { error: { code: "invalid_request" } }, - { result: envelope }, - { input_path: "input.json", input_reason: "invalid-json" }, - null, - [], - ])("keeps ordinary or incomplete error-like data successful: %j", (value) => { - expect(isCliOperationFailure(value)).toBe(false); - }); - - it("keeps CLI metadata out of the strict canonical error schema", () => { - expect(analysisErrorProjectionSchema.parse(projection)).toEqual(projection); - for (const metadata of [ - { error: "Application workflow failed" }, - { input_path: "input.json" }, - { input_reason: "invalid-json" }, - { extra: true }, - ]) - expect( - analysisErrorProjectionSchema.safeParse({ ...projection, ...metadata }) - .success, - ).toBe(false); - }); -}); diff --git a/src/cliLogging.test.ts b/src/cliLogging.test.ts index dc0544109..fbd0f9bfc 100644 --- a/src/cliLogging.test.ts +++ b/src/cliLogging.test.ts @@ -24,60 +24,19 @@ import { type UninstallHost, } from "./application/Uninstall.js"; import { CLI_COMMANDS } from "./cliCommandNames.js"; -import { isProcessCliFailure } from "./application/process/ProcessCli.js"; -describe("CLI operation status classification", () => { - it.each([ - [ - "projected error", - projectAnalysisError(new ConfigurationError("invalid setting")), - ], - [ - "MCP-shaped projected error", - { - error: projectAnalysisError(new ConfigurationError("invalid setting")), - }, - ], - ["unhealthy diagnostic", { healthy: false, checks: [] }], - ])("classifies %s as failure", (_label, value) => { - expect(isCliOperationFailure(value)).toBe(true); - }); - - it.each([ - [ - "ordinary data with code", - { code: "configuration_invalid", message: "source data" }, - ], - [ - "evidence about an error", - { - result: projectAnalysisError(new ConfigurationError("source setting")), - }, - ], - ["requested dry run", { status: "planned" }], - ["partial analysis", { status: "partial" }], - ["unsupported facet with evidence", { status: "unsupported" }], - ["cancelled setup", { status: "cancelled" }], - ["ready setup", { status: "ready" }], - ["complete uninstall", { status: "complete" }], - ["current version", { status: "current" }], - ["completed update", { status: "updated" }], - ["healthy diagnostics", { healthy: true, checks: [] }], - ["bounded evidence", { evidence: [{ truncated: true }] }], - ])("keeps %s successful", (_label, value) => { - expect(isCliOperationFailure(value)).toBe(false); - }); - - it("uses the process command's typed error output", () => { - expect( - isProcessCliFailure({ - error: "Process command failed", - category: "invalid_input", - message: "The capture input is invalid.", - }), - ).toBe(true); - expect(isProcessCliFailure({ error: "data about an error" })).toBe(false); - }); +it("does not treat ordinary error-looking data or nested Evidence as command failure", () => { + expect( + isCliOperationFailure({ + code: "configuration_invalid", + message: "source data", + }), + ).toBe(false); + expect( + isCliOperationFailure({ + result: projectAnalysisError(new ConfigurationError("source setting")), + }), + ).toBe(false); }); describe("CLI command outcome classification", () => { diff --git a/src/cliReferenceSourceImportStatus.test.ts b/src/cliReferenceSourceImportStatus.test.ts deleted file mode 100644 index 7eccab44f..000000000 --- a/src/cliReferenceSourceImportStatus.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import pino from "pino"; -import { describe, expect, it } from "vitest"; - -import { - projectReferenceSourceImportError, - type ReferenceSourceImportError, -} from "./application/ReferenceSourceImportTypes.js"; -import { isReferenceSourceImportCliFailure } from "./cli/referenceSourceImportStatus.js"; -import { isCliOperationFailure, logCliCommand } from "./cliLogging.js"; -import { ConfigurationError } from "./domain/configurationErrors.js"; -import { projectAnalysisError } from "./domain/analysisErrorProjection.js"; - -const importFailure = (code: ReferenceSourceImportError["code"]) => ({ - error: "Import failed", - ...projectReferenceSourceImportError({ - tag: "reference-source-import", - code, - message: "Internal import diagnostic", - }), -}); - -const configurationFailure = { - error: "Import failed", - ...projectAnalysisError(new ConfigurationError("Invalid import setting")), -}; - -const invalidRootFailure = importFailure("invalid-root"); - -const successfulValues: readonly (readonly [string, unknown])[] = [ - ["undefined", undefined], - ["null", null], - ["array", [invalidRootFailure]], - ["string", "Import failed"], - ["missing error label", { category: "invalid_input", message: "failure" }], - ["missing category", { error: "Import failed", message: "failure" }], - ["missing message", { error: "Import failed", category: "invalid_input" }], - ["empty message", { ...invalidRootFailure, message: "" }], - ["non-string message", { ...invalidRootFailure, message: 1 }], - ["null message", { ...invalidRootFailure, message: null }], - ["empty category", { ...invalidRootFailure, category: "" }], - ["non-string category", { ...invalidRootFailure, category: 1 }], - ["near category", { ...invalidRootFailure, category: "invalid-root" }], - ["foreign category", { ...invalidRootFailure, category: "timeout" }], - ["near error label", { ...invalidRootFailure, error: "Import failure" }], - ["label suffix", { ...invalidRootFailure, error: "Import failed " }], - ["empty error label", { ...invalidRootFailure, error: "" }], - ["non-string error label", { ...invalidRootFailure, error: true }], - ["extra field", { ...invalidRootFailure, source: "ordinary data" }], - ["extra undefined field", { ...invalidRootFailure, source: undefined }], - ["nested legacy error", { error: invalidRootFailure }], - ["ordinary error-like data", { error: "source error", message: "data" }], - [ - "ordinary code and message", - { code: "configuration_invalid", message: "data" }, - ], - ["nested evidence", { result: invalidRootFailure }], - ["partial result", { status: "partial" }], - ["unsupported result", { status: "unsupported" }], - ["successful result", { status: "complete", entries: [] }], -]; - -describe("reference-source import CLI failure classification", () => { - it.each(["cancelled", "invalid-root", "unsupported", "io", "parse"] as const)( - "recognizes the projected %s failure only at this command boundary", - (code) => { - const value = importFailure(code); - expect(isCliOperationFailure(value)).toBe(false); - expect(isReferenceSourceImportCliFailure(value)).toBe(true); - }, - ); - - it("retains canonical configuration failure classification", () => { - expect(isReferenceSourceImportCliFailure(configurationFailure)).toBe(true); - }); - - it.each(successfulValues)("keeps %s successful", (_label, value) => { - expect(isReferenceSourceImportCliFailure(value)).toBe(false); - }); -}); - -describe("reference-source import CLI logging seam", () => { - it.each([ - ["cancelled", importFailure("cancelled"), true], - ["invalid-root", invalidRootFailure, true], - ["unsupported", importFailure("unsupported"), true], - ["io", importFailure("io"), true], - ["parse", importFailure("parse"), true], - ["configuration", configurationFailure, true], - ["success", { status: "complete", entries: [] }, false], - ] as const)( - "preserves %s output and logs its status", - async (_label, value, failed) => { - const records: unknown[] = []; - const logger = pino( - { level: "info" }, - { - write: (message) => { - records.push(JSON.parse(message) as unknown); - }, - }, - ); - const previousExitCode = process.exitCode; - try { - process.exitCode = undefined; - const output = await logCliCommand( - logger, - "import-reference-source", - async () => value, - isReferenceSourceImportCliFailure, - ); - expect(output).toBe(value); - expect.soft(process.exitCode).toBe(failed ? 1 : undefined); - expect(records).toEqual([ - expect.objectContaining({ - command: "import-reference-source", - status: failed ? "error" : "ok", - level: failed ? 50 : 30, - msg: failed ? "CLI command failed" : "CLI command completed", - }), - ]); - } finally { - process.exitCode = previousExitCode; - } - }, - ); -}); diff --git a/src/contracts/sessionPathInputs.test.ts b/src/contracts/sessionPathInputs.test.ts index 2841fc1a1..074bf7f56 100644 --- a/src/contracts/sessionPathInputs.test.ts +++ b/src/contracts/sessionPathInputs.test.ts @@ -170,12 +170,6 @@ it("preserves whitespace in selected browser and Electron filesystem names", () }); }); -it("keeps evidence bundle export overwrite disabled by default", () => { - expect( - exportEvidenceBundleInputSchema.safeParse({ path: "/tmp/bundle.json" }), - ).toMatchObject({ success: true, data: { overwrite: false } }); -}); - describe.runIf(process.platform === "win32")( "Windows absolute path forms", () => { diff --git a/src/contracts/workflowInputContracts.test.ts b/src/contracts/workflowInputContracts.test.ts index 5e3f90a02..32e1ddf02 100644 --- a/src/contracts/workflowInputContracts.test.ts +++ b/src/contracts/workflowInputContracts.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vitest"; import { traceJavaScriptSemanticsRequestSchema } from "./javascript/applicationWorkflowInputContracts.js"; -import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js"; import { JAVASCRIPT_FEATURE_TRACE_EXAMPLE } from "./javascript/javascriptApplicationWorkflowExamples.js"; import { MANAGED_APPLICATION_GRAPH_EXAMPLE, @@ -63,13 +62,4 @@ describe("workflow input contracts", () => { managedApplicationGraphReferenceInputSchema.safeParse({}).success, ).toBe(false); }); - - it("accepts an explicit artifact integrity continuation policy", () => { - const input = { integrity_policy: "record-and-continue" as const }; - const inspect = ARTIFACT_TOOL_CONTRACTS.find( - ({ name }) => name === "inspect_artifact", - ); - if (inspect === undefined) throw new Error("Missing inspect_artifact"); - expect(inspect.inputSchema.safeParse(input).success).toBe(true); - }); }); diff --git a/src/domain/analysisProfile.test.ts b/src/domain/analysisProfile.test.ts index 6e5697d8c..1fb18f0ae 100644 --- a/src/domain/analysisProfile.test.ts +++ b/src/domain/analysisProfile.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest"; import { analysisProfileSchema, - analysisProfilesEqual, createAnalysisProfile, } from "./analysisProfile.js"; import type { JsonValue } from "./jsonValue.js"; @@ -14,20 +13,6 @@ const PROVIDER = { } as const; describe("analysis profile commitments", () => { - it("canonicalizes parameter key order and validates its digest", () => { - const first = createAnalysisProfile(PROVIDER, { - architecture: "arm64", - analyzers: { strings: true, functions: true }, - }); - const reordered = createAnalysisProfile(PROVIDER, { - analyzers: { functions: true, strings: true }, - architecture: "arm64", - }); - expect(reordered.digest).toBe(first.digest); - expect(analysisProfilesEqual(first, reordered)).toBe(true); - expect(analysisProfileSchema.parse(first)).toEqual(first); - }); - it("separates provider builds and semantic parameters", () => { const baseline = createAnalysisProfile(PROVIDER, { loader: "default" }); const changedBuild = createAnalysisProfile( diff --git a/src/domain/apple/plistValue.test.ts b/src/domain/apple/plistValue.test.ts index 1b547d56f..4a3465a15 100644 --- a/src/domain/apple/plistValue.test.ts +++ b/src/domain/apple/plistValue.test.ts @@ -2,33 +2,7 @@ import { expect, it } from "vitest"; import { projectPlistValue } from "./plistValue.js"; -it("projects plist data, dates, and non-finite reals as typed values", () => { - expect( - projectPlistValue({ - blob: new Uint8Array([0, 1, 2]), - when: new Date("2020-01-01T00:00:00Z"), - nested: [{ ratio: 0.5, missing: Number.NaN, unbounded: -Infinity }], - plain: { "": "empty key", flag: true, count: 42 }, - }), - ).toEqual({ - value: { - blob: { $plist_type: "data", base64: "AAEC" }, - when: { $plist_type: "date", iso8601: "2020-01-01T00:00:00.000Z" }, - nested: [ - { - ratio: 0.5, - missing: { $plist_type: "real", value: null }, - unbounded: { $plist_type: "real", value: null }, - }, - ], - plain: { "": "empty key", flag: true, count: 42 }, - }, - unknownRealCount: 2, - }); -}); - -it("rejects values a plist decoder cannot produce", () => { - expect(() => projectPlistValue({ value: Symbol("x") })).toThrow(); +it("rejects excessive plist nesting without exhausting the stack", () => { const deep: unknown[] = []; let cursor = deep; for (let depth = 0; depth < 200; depth += 1) { diff --git a/src/domain/artifactIdentity.test.ts b/src/domain/artifactIdentity.test.ts deleted file mode 100644 index b93ce450d..000000000 --- a/src/domain/artifactIdentity.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { expect, it } from "vitest"; - -import { - artifactContradictionId, - artifactEdgeId, - artifactGraphDigest, - artifactIdForContent, - artifactManifestId, - occurrenceIdForLocation, -} from "./artifactIdentity.js"; -import { appleProjectionId } from "./apple/appleApplication.js"; - -it("keeps content identity separate from occurrence location", () => { - const root = artifactIdForContent("a".repeat(64)); - expect(root).toBe( - "art_91d55c997599a1b301a52f2ad8559a9f2bfa28927d7cb2c391f3cedf6072ccdd", - ); - expect(artifactIdForContent("a".repeat(64))).toBe(root); - expect( - occurrenceIdForLocation({ - rootArtifactId: "art_root", - logicalPath: "one.bin", - entryKind: "file", - }), - ).toBe( - "occ_e6b5ac5042e4f050a3cb25f5af8419660c01f19523189470161f44113b4c16ec", - ); - expect( - occurrenceIdForLocation({ - rootArtifactId: root, - logicalPath: "one.bin", - entryKind: "file", - }), - ).not.toBe( - occurrenceIdForLocation({ - rootArtifactId: root, - logicalPath: "two.bin", - entryKind: "file", - }), - ); - expect( - occurrenceIdForLocation({ - rootArtifactId: root, - logicalPath: "one.bin", - entryKind: "file", - }), - ).not.toBe( - occurrenceIdForLocation({ - rootArtifactId: artifactIdForContent("b".repeat(64)), - logicalPath: "one.bin", - entryKind: "file", - }), - ); -}); - -it("commits to graph arrays in the order established by their owner", () => { - const nodes = [ - { artifact_id: "art-a", sha256: "a" }, - { artifact_id: "art-b", sha256: "b" }, - ] as never; - const occurrences = [ - { occurrence_id: "occ-a", logical_path: "a" }, - { occurrence_id: "occ-b", logical_path: "b" }, - ] as never; - const edges = [{ edge_id: "edge-a" }] as never; - const contradictions = [] as never; - const graph = artifactGraphDigest({ - nodes, - occurrences, - edges, - contradictions, - }); - expect( - artifactGraphDigest({ - nodes: [], - occurrences: [], - edges: [], - contradictions: [], - }), - ).toBe("d9b34ff5b7099912cce6c39343453ebc7318febd2ed75205ce21caf27113e98f"); - expect( - artifactGraphDigest({ - nodes: [ - { artifact_id: "art-a", sha256: "changed-bytes" }, - nodes[1], - ] as never, - occurrences, - edges, - contradictions, - }), - ).not.toBe(graph); - expect( - artifactGraphDigest({ - nodes, - occurrences, - edges, - contradictions: [{ contradiction_id: "ic-a" }] as never, - }), - ).not.toBe(graph); - const orderedContradictions = [ - { - contradiction_id: "ic-z", - logical_path: "z", - observed_sha256: "a", - }, - { - contradiction_id: "ic-a", - logical_path: "a", - observed_sha256: "b", - }, - ] as never; - const contradictionGraph = artifactGraphDigest({ - nodes: [], - occurrences: [], - edges: [], - contradictions: orderedContradictions, - }); - const reorderedContradictionGraph = artifactGraphDigest({ - nodes: [], - occurrences: [], - edges: [], - contradictions: [...orderedContradictions].reverse(), - }); - expect(contradictionGraph).toBe( - "121f28fb3c5f104e357d502c29994961aea68be22f7f8bcae6c90e540904ddc5", - ); - expect(reorderedContradictionGraph).toBe( - "f7ba200f36804975789ee85fab32c4f79922c8a9e603b076d20bab09ba87377e", - ); - expect(reorderedContradictionGraph).not.toBe(contradictionGraph); - expect(artifactManifestId("art_root", contradictionGraph)).toBe( - "agm_e25e6ed72612cab4a39efbbcf17e35f119ef944955ad87c0cbecce1a1c126342", - ); - expect(artifactManifestId("art_root", reorderedContradictionGraph)).toBe( - "agm_a7631939867608767e773992a4d8fc672202dd1a4a234239eb9d2e50a625fedb", - ); - expect( - artifactContradictionId({ - rootArtifactId: "root", - logicalPath: "entry", - declaredSha256: "a", - observedSha256: "b", - }), - ).not.toBe( - artifactContradictionId({ - rootArtifactId: "root", - logicalPath: "entry", - declaredSha256: "a", - observedSha256: "c", - }), - ); - expect( - artifactContradictionId({ - rootArtifactId: "art_root", - logicalPath: "one.bin", - declaredSha256: "a", - observedSha256: "b", - }), - ).toBe("ic_69ee65b6c79c597ca02c91777882edec17064e15a3abeb4ed652adc7781ce4d2"); - expect(artifactManifestId("art_root", "b".repeat(64))).toBe( - "agm_3940382b43202a6700426217151879f6274e4c362c3728368c84af993fa1f9a6", - ); - expect( - artifactEdgeId({ - parent_artifact_id: "art_parent", - child_artifact_id: "art_child", - relation: "contains", - occurrence_id: "occ_child", - logical_path: "child", - }), - ).toMatch(/^edge_[a-f0-9]{64}$/u); -}); - -it("makes Apple projection identity depend on projected facts and evidence", () => { - const projection = { - source_evidence_ids: ["ev-a", "ev-b"], - classification: ["javascript", "native"], - }; - expect(appleProjectionId(projection)).toBe( - "aap_eb45cb11ec77d3c98268fa90ce32d3060760b8f70a534fc9255cdb92de316bf9", - ); - expect( - appleProjectionId({ ...projection, classification: ["native"] }), - ).not.toBe(appleProjectionId(projection)); - expect( - appleProjectionId({ - ...projection, - source_evidence_ids: ["ev-a", "ev-c"], - }), - ).not.toBe(appleProjectionId(projection)); -}); diff --git a/src/domain/browserNetworkEvidence.test.ts b/src/domain/browserNetworkEvidence.test.ts index 588197a4b..df2afe1d0 100644 --- a/src/domain/browserNetworkEvidence.test.ts +++ b/src/domain/browserNetworkEvidence.test.ts @@ -2,7 +2,6 @@ import { createHash } from "node:crypto"; import { expect, it } from "vitest"; import { browserNetworkBodySchema } from "./browserNetworkEvidence.js"; -import { browserScenarioSchema } from "./browserScenario.js"; const bytes = Buffer.from([0xff, 0, 0xfe]); const retained = { @@ -27,28 +26,3 @@ it("validates the actual retained bytes against canonical base64, count, and dig browserNetworkBodySchema.safeParse({ ...retained, ...mutation }).success, ).toBe(false); }); - -it("defaults content selection independently and rejects unsupported controls", () => { - const input = { - browser: { mode: "launch", executable_path: "/fixture/chrome" }, - start_url: { url: "https://example.test" }, - actions: [{ step_id: "done", action: "wait_for_timeout", duration_ms: 1 }], - }; - expect(browserScenarioSchema.parse(input).capture.network).toEqual({ - request_body: false, - response_body: false, - header_values: false, - }); - expect( - browserScenarioSchema.parse({ - ...input, - capture: { network: { response_body: true } }, - }).capture.network, - ).toEqual({ request_body: false, response_body: true, header_values: false }); - expect( - browserScenarioSchema.safeParse({ - ...input, - capture: { network: { refetch: true } }, - }).success, - ).toBe(false); -}); diff --git a/src/domain/browserObservation.test.ts b/src/domain/browserObservation.test.ts index a93ed5e79..8270b669d 100644 --- a/src/domain/browserObservation.test.ts +++ b/src/domain/browserObservation.test.ts @@ -3,13 +3,9 @@ import { describe, expect, it } from "vitest"; import { browserEndpointSchema, browserOriginSchema, - inspectWebPageInputSchema, - isLiteralLoopbackHostname, - listBrowserTargetsInputSchema, sanitizeEndpointCandidate, sanitizeBrowserUrl, } from "./browserObservation.js"; -import { captureWebScreenshotInputSchema } from "./webScreenshot.js"; describe("browser observation contracts", () => { it("normalizes exact HTTP origins without accepting broader URL scopes", () => { @@ -45,82 +41,9 @@ describe("browser observation contracts", () => { ]) expect(browserEndpointSchema.safeParse(value).success, value).toBe(false); }); - - it("recognizes bracketed and normalized IPv6 loopback hostnames", () => { - for (const hostname of ["127.0.0.1", "[::1]", "::1"]) - expect(isLiteralLoopbackHostname(hostname), hostname).toBe(true); - for (const hostname of ["localhost", "127.0.0.2", "::2"]) - expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false); - }); - - it("applies defaults and rejects unknown public observation input fields", () => { - expect( - listBrowserTargetsInputSchema.parse({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - }), - ).toEqual({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - }); - expect( - inspectWebPageInputSchema.parse({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: "page-1", - }), - ).toMatchObject({ - observation_ms: 500, - include_accessibility_text: false, - include_console_text: false, - include_json_body_shapes: false, - include_websocket_shapes: false, - include_script_sources: false, - include_storage_keys: false, - }); - expect( - inspectWebPageInputSchema.safeParse({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: "page-1", - unknown_field: true, - }).success, - ).toBe(false); - }); }); describe("browser observation sensitive surfaces and retention", () => { - it("accepts selected sensitive capture surfaces without extra flags", () => { - const base = { - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: "page-1", - }; - for (const input of [ - { include_console_text: true }, - { include_json_body_shapes: true }, - { include_websocket_shapes: true }, - ]) - expect( - inspectWebPageInputSchema.safeParse({ ...base, ...input }).success, - ).toBe(true); - expect( - inspectWebPageInputSchema.safeParse({ - ...base, - include_storage_fingerprints: true, - }).success, - ).toBe(false); - }); - - it("accepts screenshot capture without an extra approval flag", () => { - const input = { - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: "page-1", - }; - expect(captureWebScreenshotInputSchema.safeParse(input).success).toBe(true); - }); - it("removes only URL userinfo and preserves the original query and fragment", () => { expect( sanitizeBrowserUrl( diff --git a/src/domain/canonicalDigest.test.ts b/src/domain/canonicalDigest.test.ts index 6a18a2ad0..09b67c3a6 100644 --- a/src/domain/canonicalDigest.test.ts +++ b/src/domain/canonicalDigest.test.ts @@ -6,7 +6,7 @@ import { describe, expect } from "vitest"; import { digestCanonicalValue } from "./canonicalDigest.js"; -const canonicalizeDigest = (value: unknown): string => { +const legacyDigest = (value: unknown): string => { const encoded = canonicalize(value); if (encoded === undefined) throw new TypeError("Unserializable fixture"); return createHash("sha256").update(encoded).digest("hex"); @@ -16,7 +16,7 @@ describe("incremental canonical digest", () => { it.prop([fc.jsonValue()])( "preserves canonicalize digests for JSON values", (value) => { - expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); + expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); }, ); @@ -25,7 +25,7 @@ describe("incremental canonical digest", () => { const sparse: unknown[] = [undefined, Symbol("omit"), () => undefined]; sparse.length = 6; const fixtures: unknown[] = [ - { "\ue000": "bmp", 𐀀: "supplementary" }, + { "\uE000": "BMP", "\u{10000}": "supplementary" }, { "€": "\ud800", "😀": "\udc00", @@ -41,7 +41,7 @@ describe("incremental canonical digest", () => { { nested: { toJSON: () => undefined } }, ]; for (const value of fixtures) - expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); + expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); }); it("rejects unsupported roots, non-finite numbers, BigInt and ancestor cycles", () => { @@ -56,18 +56,15 @@ describe("incremental canonical digest", () => { expect(() => digestCanonicalValue(value)).toThrow(); }); - it("hashes repeated large leaves with the same byte sequence", () => { - const value = { - payload: Array.from({ length: 64 }, () => "x".repeat(16_384)), - }; - expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); - }); - - it("keeps digests identical when buffered parts cross flush boundaries", () => { + it("preserves canonical bytes across large keys, repeated leaves and buffer flushes", () => { const manyKeys: Record = {}; for (let i = 0; i < 2000; i += 1) manyKeys[`k${i}`] = i; - const value = { keys: manyKeys, tail: ["€", "😀", "x".repeat(9000)] }; - expect(digestCanonicalValue(value)).toBe(canonicalizeDigest(value)); + const value = { + keys: manyKeys, + payload: Array.from({ length: 64 }, () => "x".repeat(16_384)), + tail: ["€", "😀", "x".repeat(9000)], + }; + expect(digestCanonicalValue(value)).toBe(legacyDigest(value)); }); it("preserves canonicalize property access and toJSON cycle behavior", () => { @@ -81,11 +78,11 @@ describe("incremental canonical digest", () => { }; }; expect(digestCanonicalValue(createAccessor())).toBe( - canonicalizeDigest(createAccessor()), + legacyDigest(createAccessor()), ); const shared = { toJSON: () => ({ answer: 42 }) }; expect(digestCanonicalValue([shared, shared])).toBe( - canonicalizeDigest([shared, shared]), + legacyDigest([shared, shared]), ); }); }); diff --git a/src/domain/canonicalDigest.ts b/src/domain/canonicalDigest.ts index 3c4f9e3c6..9e24aa536 100644 --- a/src/domain/canonicalDigest.ts +++ b/src/domain/canonicalDigest.ts @@ -1,6 +1,11 @@ import { createHash } from "node:crypto"; -/** Hash canonicalize-compatible JSON without assembling an aggregate string. */ +/** + * Streaming SHA-256 over canonical JSON. Hashing owner (avoids assembling + * aggregate strings); `comparisonSemantics.canonicalJson` (canonicalize lib) + * is the string-comparison owner. JSON object keys follow RFC 8785's UTF-16 + * code-unit order in both; entity-list ordering is a separate concern. + */ export const digestCanonicalValue = ( value: unknown, context = "Comparison", @@ -64,6 +69,7 @@ const emitCanonical = ( } else { emit("{"); let first = true; + // Match canonicalize/RFC 8785, including supplementary-plane keys. for (const key of Object.keys(value).sort()) { if ( Reflect.get(value, key) === undefined || diff --git a/src/domain/changedBehavior.ts b/src/domain/changedBehavior.ts index bd14cee31..b785cdd23 100644 --- a/src/domain/changedBehavior.ts +++ b/src/domain/changedBehavior.ts @@ -2,7 +2,10 @@ import { z } from "zod"; import { artifactComparisonResultSchema } from "./artifactComparison.js"; import { uniqueSorted } from "./canonicalOrdering.js"; -import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; +import { + compositeKey, + compareUnicodeCodePoints, +} from "./unicodeCodePointOrder.js"; import { comparisonSourceEvidenceIds } from "./comparisonSourceEvidence.js"; import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js"; import { functionComparisonResultSchema } from "./functionComparisonSchemas.js"; @@ -389,11 +392,9 @@ const count = ( .length; const compareFindings = (left: Finding, right: Finding): number => - compareUnicodeCodePoints(left.scope, right.scope) || - compareUnicodeCodePoints(left.dimension, right.dimension) || compareUnicodeCodePoints( - left.source_comparison_id, - right.source_comparison_id, + compositeKey([left.scope, left.dimension, left.source_comparison_id]), + compositeKey([right.scope, right.dimension, right.source_comparison_id]), ); const assertUnique = (values: readonly string[], label: string): void => { diff --git a/src/domain/digests.test.ts b/src/domain/digests.test.ts deleted file mode 100644 index 7beb70881..000000000 --- a/src/domain/digests.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - digestSchema, - isDigest, - isPrefixedDigest, - prefixedDigestSchema, -} from "./digests.js"; - -const DIGEST = "a".repeat(64); -const OTHER_DIGEST = "b".repeat(64); - -describe("digest shapes", () => { - it("accepts a lowercase hex sha256", () => { - expect(digestSchema.parse(DIGEST)).toBe(DIGEST); - expect(isDigest(DIGEST)).toBe(true); - }); - - it.each([ - ["uppercase", DIGEST.toUpperCase()], - ["too short", "a".repeat(63)], - ["too long", "a".repeat(65)], - ["non-hex", "g".repeat(64)], - ["prefixed", `ev_${DIGEST}`], - ])("rejects a %s digest", (_label, value) => { - expect(digestSchema.safeParse(value).success).toBe(false); - expect(isDigest(value)).toBe(false); - }); - - it("rejects non-string values", () => { - for (const value of [null, undefined, 42, {}, []]) - expect(isDigest(value)).toBe(false); - }); - - it("keeps identifier families apart", () => { - expect(prefixedDigestSchema("ev").parse(`ev_${DIGEST}`)).toBe( - `ev_${DIGEST}`, - ); - // The point of the prefix: an identifier from one family must not satisfy - // another, or a mis-pasted id would resolve to the wrong object. - expect(prefixedDigestSchema("ev").safeParse(`art_${DIGEST}`).success).toBe( - false, - ); - expect(prefixedDigestSchema("ev").safeParse(DIGEST).success).toBe(false); - expect(isPrefixedDigest(`ev_${DIGEST}`, "ev")).toBe(true); - expect(isPrefixedDigest(`ev_${DIGEST}`, "art")).toBe(false); - }); - - it("distinguishes nested prefixes from their common ancestor", () => { - // `jag_node_` must not validate as `jag_` even though it starts with it. - expect( - prefixedDigestSchema("jag").safeParse(`jag_node_${DIGEST}`).success, - ).toBe(false); - expect(prefixedDigestSchema("jag_node").parse(`jag_node_${DIGEST}`)).toBe( - `jag_node_${DIGEST}`, - ); - expect(prefixedDigestSchema("jag").parse(`jag_${OTHER_DIGEST}`)).toBe( - `jag_${OTHER_DIGEST}`, - ); - }); -}); diff --git a/src/domain/digests.ts b/src/domain/digests.ts index f46beccc2..0c1eee886 100644 --- a/src/domain/digests.ts +++ b/src/domain/digests.ts @@ -35,8 +35,3 @@ export const prefixedDigestSchema = (prefix: string): z.ZodString => /** True when `value` is a bare digest. */ export const isDigest = (value: unknown): value is string => typeof value === "string" && SHA256_PATTERN.test(value); - -/** True when `value` is a digest carrying `prefix`. */ -export const isPrefixedDigest = (value: unknown, prefix: string): boolean => - typeof value === "string" && - prefixedDigestSchema(prefix).safeParse(value).success; diff --git a/src/domain/dosCom.test.ts b/src/domain/dosCom.test.ts deleted file mode 100644 index 933939722..000000000 --- a/src/domain/dosCom.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { executableFormatHintSchema, validateDosComLength } from "./dosCom.js"; - -describe("explicit DOS COM interpretation", () => { - it.each([1, 0xff00])("admits the segment extent %i", (length) => { - expect(validateDosComLength(length).ok).toBe(true); - }); - it.each([0, -1, 0xff01, 1.5, NaN, Infinity])( - "rejects invalid extent %i", - (length) => { - expect(validateDosComLength(length).ok).toBe(false); - }, - ); - it("does not turn arbitrary format names into raw COM", () => { - expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true); - expect(executableFormatHintSchema.safeParse("raw").success).toBe(false); - }); -}); diff --git a/src/domain/evm/evmInterface.test.ts b/src/domain/evm/evmInterface.test.ts index 659f838ba..93ab32add 100644 --- a/src/domain/evm/evmInterface.test.ts +++ b/src/domain/evm/evmInterface.test.ts @@ -2,11 +2,6 @@ import { expect, it } from "vitest"; import { evmInterfaceSchema } from "./evmInterface.js"; import { evmInterfaceFixture } from "../../../tests/fixtures/evm/interface.js"; -it("preserves original carrier and decoded byte identity as distinct observations", () => { - const fixture = evmInterfaceFixture(); - expect(evmInterfaceSchema.parse(fixture)).toEqual(fixture); - expect(fixture.artifact.sha256).not.toBe(fixture.bytecode.sha256); -}); it.each(["byte-count", "body-offset", "selector", "authenticity"])( "rejects false interface evidence: %s", (problem) => { diff --git a/src/domain/functionComparison.test.ts b/src/domain/functionComparison.test.ts index 226fbb716..f846217c5 100644 --- a/src/domain/functionComparison.test.ts +++ b/src/domain/functionComparison.test.ts @@ -143,7 +143,7 @@ describe("function comparison normalized identity", () => { }, ); - it.each(["sub_deadbeef", "fcn.00401000", "FUN_00401000", "FUN_deadBEEF"])( + it.each(["sub_deadbeef", "fcn.00401000", "FUN_deadBEEF"])( "keeps %s as an address-derived name", (name) => { const generated = (base: "0x1000" | "0x2000") => diff --git a/src/domain/javascript/electronStaticAnalysisIpc.ts b/src/domain/javascript/electronStaticAnalysisIpc.ts index 5221c26bd..9efc2670b 100644 --- a/src/domain/javascript/electronStaticAnalysisIpc.ts +++ b/src/domain/javascript/electronStaticAnalysisIpc.ts @@ -17,6 +17,7 @@ import { range, } from "./javascriptStaticAnalysisHelpers.js"; import { semanticStaticPropertyName } from "./javascriptAstValues.js"; +import { compositeKey } from "../unicodeCodePointOrder.js"; import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js"; /** Inspect Electron IPC operations and validation candidates. */ @@ -161,7 +162,14 @@ const addValidation = ( }; addLocatedFinding(context, { collection: context.accumulator.senderValidations, - key: `electron-validation\0${input.subject}\0${input.mechanism}\0${input.expected.status === "literal" ? String(input.expected.value) : input.expected.expression}`, + key: compositeKey([ + "electron-validation", + input.subject, + input.mechanism, + input.expected.status === "literal" + ? String(input.expected.value) + : input.expected.expression, + ]), node, value: finding, }); diff --git a/src/domain/javascript/electronStaticAnalysisNative.ts b/src/domain/javascript/electronStaticAnalysisNative.ts index 1aef90f1a..73b2d8b9d 100644 --- a/src/domain/javascript/electronStaticAnalysisNative.ts +++ b/src/domain/javascript/electronStaticAnalysisNative.ts @@ -1,6 +1,9 @@ import * as t from "@babel/types"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../unicodeCodePointOrder.js"; import { stripQueryAndFragment } from "../artifactPathSyntax.js"; import type { ElectronNativeAddonBindingFinding } from "./electronStaticAnalysisTypes.js"; import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js"; @@ -141,7 +144,9 @@ const addBinding = (input: NativeBindingInput): void => { const members = unique.length === 0 ? ["*"] : unique; addLocatedFinding(context, { collection: context.accumulator.nativeAddonBindings, - key: `native-addon-binding\0${kind}\0${specifier}\0${members.join("\0")}`, + // Members are a variable-length source-derived list: compositeKey keeps + // ["a\0b"] distinct from ["a", "b"] instead of collapsing one binding. + key: compositeKey(["native-addon-binding", kind, specifier, members]), node, value: { specifier, diff --git a/src/domain/javascript/javascriptApplicationVersionKeys.ts b/src/domain/javascript/javascriptApplicationVersionKeys.ts index 134acd657..081968f3f 100644 --- a/src/domain/javascript/javascriptApplicationVersionKeys.ts +++ b/src/domain/javascript/javascriptApplicationVersionKeys.ts @@ -1,5 +1,8 @@ import { canonicalJson } from "../comparisonSemantics.js"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../unicodeCodePointOrder.js"; import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js"; import type { JsonValue } from "../jsonValue.js"; @@ -295,7 +298,7 @@ const uniqueStringProperty = ( const joined = (...values: readonly unknown[]): string | null => { const strings = values.map(nonEmptyString); - return strings.some((value) => value === null) ? null : strings.join("\0"); + return strings.some((value) => value === null) ? null : compositeKey(strings); }; const nonEmptyString = (value: unknown): string | null => diff --git a/src/domain/javascript/javascriptFeatureSeed.array_members.test.ts b/src/domain/javascript/javascriptFeatureSeed.array_members.test.ts index 419cd1923..00bddb649 100644 --- a/src/domain/javascript/javascriptFeatureSeed.array_members.test.ts +++ b/src/domain/javascript/javascriptFeatureSeed.array_members.test.ts @@ -40,101 +40,116 @@ const matchingModes = [ describe.each(memberFields)( "$kind seeds for $nodeKind / $field", ({ kind, nodeKind, field }) => { - it.each(matchingModes)( - "matches scalar and array values with $match / $value / case-sensitive $case_sensitive", - (mode) => { - const values: readonly [JsonValue, string][] = [ - ["openProject", ""], - [["closeProject", "openProject"], "[1]"], - ]; - for (const [value, suffix] of values) { - const node = memberNode(nodeKind, { [field]: value }); - expect( - findApplicationFeatureSeeds([node], { kind, ...mode }), - ).toEqual([propertyMatch(node, `${field}${suffix}`)]); - } - }, - ); - - it("keeps exact, case-sensitive, and non-string exclusions", () => { - const node = memberNode(nodeKind, { - [field]: [null, 42, true, "openProject"], - }); - for (const value of ["Project", "OPENPROJECT", "42", "true", "null"]) - expect(findApplicationFeatureSeeds([node], seed(kind, value))).toEqual( - [], - ); - expect( - findApplicationFeatureSeeds([node], { - ...seed(kind, "Project"), - match: null, - }), - ).toEqual([]); - }); - - it("retains actual indexes through nested arrays and object properties", () => { - const properties = { - nested: [{ [field]: [null, 42, false, [["openProject"]]] }], - }; - const node = memberNode(nodeKind, properties); - const before = structuredClone(node); - - expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([ - propertyMatch(node, `nested[0].${field}[3][0][0]`), - ]); - expect(node).toEqual(before); - expect(properties.nested[0]?.[field]).toEqual([ - null, - 42, - false, - [["openProject"]], - ]); - }); - - it("preserves literal dotted-field suffixes for scalars and arrays", () => { + it("retains scalar and array member locations", () => { const values: readonly [JsonValue, string][] = [ ["openProject", ""], - [["openProject"], "[0]"], + [["closeProject", "openProject"], "[1]"], ]; for (const [value, suffix] of values) { - const node = memberNode(nodeKind, { [`nested.${field}`]: value }); + const node = memberNode(nodeKind, { [field]: value }); expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([ - propertyMatch(node, `nested.${field}${suffix}`), - ]); - } - }); - - it("does not select near-fields, literal bracket keys, or object descendants", () => { - const cases = [ - { - properties: { [`other_${field}`]: "openProject" }, - path: `other_${field}`, - }, - { properties: { [`${field}[0]`]: "openProject" }, path: `${field}[0]` }, - { - properties: { [`nested.${field}[0]`]: ["openProject"] }, - path: `nested.${field}[0][0]`, - }, - { - properties: { [field]: { name: "openProject" } }, - path: `${field}.name`, - }, - { - properties: { [field]: [{ name: "openProject" }] }, - path: `${field}[0].name`, - }, - ]; - for (const { properties, path } of cases) { - const node = memberNode(nodeKind, properties); - expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([]); - expect(findApplicationFeatureSeeds([node], seed("string"))).toEqual([ - propertyMatch(node, path), + propertyMatch(node, `${field}${suffix}`), ]); } }); }, ); +describe("shared array-member matching semantics", () => { + const kind = "api"; + const nodeKind = "context-bridge-api"; + const field = "members"; + + it.each(matchingModes)( + "matches $match / $value / case-sensitive $case_sensitive", + (mode) => { + const node = memberNode(nodeKind, { + members: ["closeProject", "openProject"], + }); + expect(findApplicationFeatureSeeds([node], { kind, ...mode })).toEqual([ + propertyMatch(node, "members[1]"), + ]); + }, + ); + + it("keeps exact, case-sensitive, and non-string exclusions", () => { + const node = memberNode(nodeKind, { + [field]: [null, 42, true, "openProject"], + }); + for (const value of ["Project", "OPENPROJECT", "42", "true", "null"]) + expect(findApplicationFeatureSeeds([node], seed(kind, value))).toEqual( + [], + ); + expect( + findApplicationFeatureSeeds([node], { + ...seed(kind, "Project"), + match: null, + }), + ).toEqual([]); + }); + + it("retains actual indexes through nested arrays and object properties", () => { + const properties = { + nested: [{ [field]: [null, 42, false, [["openProject"]]] }], + }; + const node = memberNode(nodeKind, properties); + const before = structuredClone(node); + + expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([ + propertyMatch(node, `nested[0].${field}[3][0][0]`), + ]); + expect(node).toEqual(before); + expect(properties.nested[0]?.[field]).toEqual([ + null, + 42, + false, + [["openProject"]], + ]); + }); + + it("preserves literal dotted-field suffixes for scalars and arrays", () => { + const values: readonly [JsonValue, string][] = [ + ["openProject", ""], + [["openProject"], "[0]"], + ]; + for (const [value, suffix] of values) { + const node = memberNode(nodeKind, { [`nested.${field}`]: value }); + expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([ + propertyMatch(node, `nested.${field}${suffix}`), + ]); + } + }); + + it("does not select near-fields, literal bracket keys, or object descendants", () => { + const cases = [ + { + properties: { [`other_${field}`]: "openProject" }, + path: `other_${field}`, + }, + { properties: { [`${field}[0]`]: "openProject" }, path: `${field}[0]` }, + { + properties: { [`nested.${field}[0]`]: ["openProject"] }, + path: `nested.${field}[0][0]`, + }, + { + properties: { [field]: { name: "openProject" } }, + path: `${field}.name`, + }, + { + properties: { [field]: [{ name: "openProject" }] }, + path: `${field}[0].name`, + }, + ]; + for (const { properties, path } of cases) { + const node = memberNode(nodeKind, properties); + expect(findApplicationFeatureSeeds([node], seed(kind))).toEqual([]); + expect(findApplicationFeatureSeeds([node], seed("string"))).toEqual([ + propertyMatch(node, path), + ]); + } + }); +}); + describe("feature seed selection controls", () => { it.each([ { kind: "api", nodeKind: "context-bridge-api", field: "label" }, diff --git a/src/domain/javascript/javascriptRecovery.test.ts b/src/domain/javascript/javascriptRecovery.test.ts deleted file mode 100644 index 4a48a44b0..000000000 --- a/src/domain/javascript/javascriptRecovery.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { javascriptRecoveryInputSchema } from "./javascriptRecovery.js"; - -describe("JavaScript recovery requests", () => { - it.each([ - { path: "", output_directory: "/tmp/recovered" }, - { path: "/tmp/bundle.js" }, - { - path: "/tmp/bundle.js", - output_directory: "/tmp/recovered", - approve: true, - }, - { - path: "/tmp/bundle.js", - output_directory: "/tmp/recovered", - extraction_mode: "invented", - }, - ])("rejects malformed input %j", (input) => { - expect(javascriptRecoveryInputSchema.safeParse(input).success).toBe(false); - }); -}); diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts index 08453a651..9292ea265 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.ts @@ -52,6 +52,8 @@ const resolveCallables = ( node: t.Node, context: CallResolutionContext, ): LocalCallableResolution => { + // `unwrapJavaScriptExpression` strips all transparent layers iteratively, + // so a single recursion step suffices (no per-layer stack growth). const unwrapped = unwrapJavaScriptExpression(node).node; if (unwrapped !== node) return resolveCallables(unwrapped, context); const direct = semanticCallableIdForNode(node); diff --git a/src/domain/javascript/javascriptSemanticQuerySchemas.test.ts b/src/domain/javascript/javascriptSemanticQuerySchemas.test.ts deleted file mode 100644 index ab64cfe00..000000000 --- a/src/domain/javascript/javascriptSemanticQuerySchemas.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { expect, it } from "vitest"; - -import { javaScriptSemanticQueryInputSchema } from "./javascriptSemanticQuerySchemas.js"; - -it("rejects a source-map authority setting that the query does not consume", () => { - expect( - javaScriptSemanticQueryInputSchema.safeParse({ - seed: { kind: "endpoint", value: "/api" }, - direction: "forward-influence", - source_map_authority: { authority: "none" }, - }).success, - ).toBe(false); -}); diff --git a/src/domain/javascript/javascriptSemanticTraversal.ts b/src/domain/javascript/javascriptSemanticTraversal.ts index 4719ce34d..9b562a94c 100644 --- a/src/domain/javascript/javascriptSemanticTraversal.ts +++ b/src/domain/javascript/javascriptSemanticTraversal.ts @@ -50,7 +50,11 @@ interface TraversalFrame { nextIndex: number; } -/** Return child Babel nodes in visitor-key order. */ +/** + * Child Babel nodes in `VISITOR_KEYS` order. Single owner for AST child + * expansion; bespoke `Object.values` / duplicated `childNodes` walkers must + * not be reintroduced (they diverge on loc/comment fields and ordering). + */ export const childNodes = (node: t.Node): t.Node[] => { const keys = t.VISITOR_KEYS[node.type]; if (keys === undefined) return []; diff --git a/src/domain/javascript/javascriptSourceParser.ts b/src/domain/javascript/javascriptSourceParser.ts index e413e0cb4..6a8016887 100644 --- a/src/domain/javascript/javascriptSourceParser.ts +++ b/src/domain/javascript/javascriptSourceParser.ts @@ -3,35 +3,51 @@ import { parse, type ParserPlugin } from "@babel/parser"; /** Babel AST produced by REA's inert JavaScript parser boundary. */ export type ParsedJavaScriptSource = ReturnType; +/** + * Babel plugins for one source path. Single owner for TypeScript/JSX + * mode selection (tsc + Babel `typescript` plugin semantics). + * + * - `dts:true` only for `.d.ts/.d.mts/.d.cts` ambient declarations; + * ordinary `.ts` keeps the missing-initializer diagnostic. + * - JSX enabled for `.tsx`, `.jsx`, `.js`, and unknown paths; disabled for + * plain `.ts/.cts/.mts` (angle-bracket assertions, not JSX) and for all + * declaration files. `.mts` (including `.d.mts`) sets + * `disallowAmbiguousJSXLike`, matching tsc's `.mts` mode. + * - `decorators-legacy` always present: without it decorated sources fail + * hard instead of reporting recovered syntax, losing every derived fact. + * - Unknown paths retain the existing JSX-capable contract (best-effort + * parse; failures surface via `errorRecovery`, never silent misparse). + */ +export const parserPluginsForPath = (sourcePath?: string): ParserPlugin[] => { + const path = sourcePath ?? ""; + const dts = /\.d\.(?:ts|mts|cts)$/iu.test(path); + const isTsLike = /\.(?:ts|cts|mts)$/iu.test(path); + const isTsx = /\.tsx$/iu.test(path); + const isMts = /\.mts$/iu.test(path); + const typescript: ParserPlugin = [ + "typescript", + { + dts, + ...(isMts ? { disallowAmbiguousJSXLike: true } : {}), + }, + ]; + const jsxCapable = !dts && (isTsx || !isTsLike); + return jsxCapable + ? ["decorators-legacy", "jsx", typescript] + : ["decorators-legacy", typescript]; +}; + /** Parse JavaScript or TypeScript once without attaching comments to AST nodes. */ export const parseJavaScriptSource = ( source: string, sourcePath?: string, ): ParsedJavaScriptSource | null => { - const path = sourcePath ?? ""; - const isMts = /\.mts$/iu.test(path); - const typescript: ParserPlugin = [ - "typescript", - { - dts: /\.d\.(?:ts|mts|cts)$/iu.test(path), - ...(isMts ? { disallowAmbiguousJSXLike: true } : {}), - }, - ]; try { return parse(source, { sourceType: "unambiguous", errorRecovery: true, attachComment: false, - // "decorators-legacy" admits both the standard and the legacy decorator - // forms, including parameter decorators. Without it a decorated - // TypeScript source fails to parse at all rather than reporting - // recovered syntax, which loses every fact derived from that source. - // TypeScript's .mts mode disables JSX and rejects ambiguous angle syntax. - // Plain .ts and .cts artifacts admit angle-bracket type assertions instead of JSX. - // Unknown paths retain the existing JSX-capable parser contract. - plugins: /\.(?:ts|cts|mts)$/iu.test(path) - ? ["decorators-legacy", typescript] - : ["decorators-legacy", "jsx", typescript], + plugins: parserPluginsForPath(sourcePath), }); } catch (cause: unknown) { // Unparseable source is represented by the null return. diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index 25cd0fcbc..8038edf44 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -16,7 +16,10 @@ import { semanticStaticPropertyName, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../unicodeCodePointOrder.js"; /** Explicit result for source text that Babel cannot parse. */ export const failedJavaScriptStaticAnalysis = (): JavaScriptStaticAnalysis => ({ @@ -674,7 +677,17 @@ export const detectVendors = (source: string): string[] => export const registrationKey = ( registration: JavaScriptBundlerRegistration, ): string => - `${registration.runtime}\0${registration.chunk_keys.join("\0")}\0${String(registration.unknown_chunk_keys)}\0${registration.modules.map(({ module_key: key, source_sha256: digest }) => `${key}:${digest}`).join("\0")}`; + // Collision-free tuple: chunk/module keys are variable-length source-derived + // lists, so NUL-joins would collapse ["a\0b"] with ["a", "b"]. + compositeKey([ + registration.runtime, + registration.chunk_keys, + String(registration.unknown_chunk_keys), + registration.modules.map(({ module_key: key, source_sha256: digest }) => [ + key, + digest, + ]), + ]); /** Sort values by a deterministic unique semantic key. */ export const sortedUnique = ( diff --git a/src/domain/javascript/javascriptStaticPathResolution.test.ts b/src/domain/javascript/javascriptStaticPathResolution.test.ts index 1c44e0682..4d3662ce6 100644 --- a/src/domain/javascript/javascriptStaticPathResolution.test.ts +++ b/src/domain/javascript/javascriptStaticPathResolution.test.ts @@ -14,16 +14,10 @@ const absoluteParts = [ ["/app", "/shared/preload.js"], ["ignored", "/app", "preload.js"], ["/app", "first", "/shared", "nested", "../preload.js"], - ["/app", "preload/"], ["/app", "preload///"], - ["/app/", "./sub", "../preload.js"], - ["/app", ".."], ["/app", "../../.."], - ["/"], ["///"], - ["/app", "/", ""], ["", "/app", "", "preload.js", ""], - ["/app", "..", "child", "..", "preload.js"], ]; const anchoredExpressions = [ @@ -38,21 +32,12 @@ const anchoredExpressions = [ 'path.resolve("ignored", path.dirname(__filename), "preload.js")', "preload.js", ], - ['path.resolve(__dirname, "sub", "../preload.js")', "preload.js"], ['path.resolve(__dirname, "../preload.js")', "../preload.js"], - ['path.resolve(__dirname, "preload/")', "preload"], ['path.resolve(__dirname, "sub", __dirname, "preload.js")', "preload.js"], ['path.resolve(__dirname, "/shared", "preload.js")', "/shared/preload.js"], - [ - 'path.resolve(dirname(fileURLToPath(import.meta.url)), "/shared/preload.js")', - "/shared/preload.js", - ], ["path.resolve(__dirname)", "."], - ['path.resolve(__dirname, "")', "."], - ['path.resolve(__dirname, "sub/../")', "."], ['path.posix.resolve(`/app`, `/shared`, "preload.js")', "/shared/preload.js"], ['path.posix.resolve("" + "/app", "preload.js")', "/app/preload.js"], - ['path.posix.resolve(`/` + `app`, "preload.js")', "/app/preload.js"], ] as const; const unknownExpressions = [ diff --git a/src/domain/javascript/sourceToBundleSignals.ts b/src/domain/javascript/sourceToBundleSignals.ts index 53dd8a842..2190988fe 100644 --- a/src/domain/javascript/sourceToBundleSignals.ts +++ b/src/domain/javascript/sourceToBundleSignals.ts @@ -1,6 +1,9 @@ import { posix } from "node:path"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../unicodeCodePointOrder.js"; import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js"; import type { HistoricalSourceGraph } from "../referenceSourceGraph.js"; import { @@ -322,15 +325,15 @@ const uniquePaths = (paths: readonly CurrentPath[]): CurrentPath[] => [ ...new Map( paths.map((path) => [ - `${path.kind}\0${path.value}\0${String(path.allowSuffix)}`, + compositeKey([path.kind, path.value, String(path.allowSuffix)]), path, ]), ).values(), - ].sort( - (left, right) => - compareUnicodeCodePoints(left.kind, right.kind) || - compareUnicodeCodePoints(left.value, right.value) || - Number(left.allowSuffix) - Number(right.allowSuffix), + ].sort((left, right) => + compareUnicodeCodePoints( + compositeKey([left.kind, left.value]), + compositeKey([right.kind, right.value]), + ), ); const pathSuffixes = (path: string): string[] => { diff --git a/src/domain/jsonShape.test.ts b/src/domain/jsonShape.test.ts index dc37bb6d4..e1a5dad2b 100644 --- a/src/domain/jsonShape.test.ts +++ b/src/domain/jsonShape.test.ts @@ -39,45 +39,19 @@ describe("inferJsonShape", () => { expect(inferJsonShape("not-json")).toBeNull(); }); - it.each([ - ["é", "e\u0301", "e\u0341"], - ["é", "e\u0341", "e\u0301"], - ["e\u0301", "é", "e\u0341"], - ["e\u0301", "e\u0341", "é"], - ["e\u0341", "é", "e\u0301"], - ["e\u0341", "e\u0301", "é"], - ])("orders distinct collation-equal paths from %j, %j, %j", (...names) => { - for (const name of names) expect(name.localeCompare("é")).toBe(0); - const values: Readonly> = { - é: 1, - "e\u0301": "value", - "e\u0341": null, - }; - const shape = inferJsonShape( - JSON.stringify( - Object.fromEntries(names.map((name) => [name, values[name]])), - ), - ); - - expect(shape).toEqual({ - root_type: "object", - node_count: 4, - max_depth_observed: 1, - properties: [ - { path: "/e\u0301", types: ["string"], observations: 1 }, - { path: "/e\u0341", types: ["null"], observations: 1 }, - { path: "/é", types: ["number"], observations: 1 }, - ], - }); - }); - - it.each([false, true])( - "preserves nested types, counts, depth and pointer names with reversed keys: %s", - (reverse) => { + it("preserves pointer escaping and code-point ordering independently of key insertion order", () => { + for (const reverse of [false, true]) { const object = (number: number, value: unknown) => { const entries = [ ["é/~", number], ["e\u0301/~", value], + ["e\u0341/~", true], + ["A", false], + ["_", false], + ["a", false], + ["z", false], + ["\u{10000}", false], + ["\uE000", false], ]; return Object.fromEntries(reverse ? entries.reverse() : entries); }; @@ -87,31 +61,30 @@ describe("inferJsonShape", () => { expect(shape).toEqual({ root_type: "object", - node_count: 9, + node_count: 23, max_depth_observed: 4, properties: [ { path: "/nested", types: ["array"], observations: 1 }, + { path: "/nested/*/A", types: ["boolean"], observations: 2 }, + { path: "/nested/*/_", types: ["boolean"], observations: 2 }, + { path: "/nested/*/a", types: ["boolean"], observations: 2 }, { path: "/nested/*/e\u0301~1~0", types: ["array", "null"], observations: 2, }, + { + path: "/nested/*/e\u0341~1~0", + types: ["boolean"], + observations: 2, + }, + { path: "/nested/*/z", types: ["boolean"], observations: 2 }, { path: "/nested/*/é~1~0", types: ["number"], observations: 2 }, + { path: "/nested/*/\uE000", types: ["boolean"], observations: 2 }, + { path: "/nested/*/\u{10000}", types: ["boolean"], observations: 2 }, ], }); - }, - ); - - it("orders paths deterministically by Unicode code point", () => { - const names = ["z", "é", "A", "_", "a"]; - // Code-point order (locale-independent): A < _ < a < z < é. - // `localeCompare` order varies by host ICU and must not leak into evidence. - const expected = ["/A", "/_", "/a", "/z", "/é"]; - const shape = inferJsonShape( - JSON.stringify(Object.fromEntries(names.map((name) => [name, true]))), - ); - - expect(shape?.properties.map(({ path }) => path)).toEqual(expected); + } }); it("retains every parsed property beyond the former shape-node limit", () => { diff --git a/src/domain/native/objcSwiftMetadata.ts b/src/domain/native/objcSwiftMetadata.ts index 6b4e13cb5..5778e5dd7 100644 --- a/src/domain/native/objcSwiftMetadata.ts +++ b/src/domain/native/objcSwiftMetadata.ts @@ -1,6 +1,9 @@ import { z } from "zod"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../unicodeCodePointOrder.js"; /** Objective-C method type. */ export const objcMethodTypeSchema = z.enum([ @@ -397,8 +400,10 @@ export const inspectNativeDispatchMetadata = ( })); const decodedImplementations = [...implementations.values()].sort( (left, right) => - compareUnicodeCodePoints(left.class_name, right.class_name) || - compareUnicodeCodePoints(left.selector, right.selector), + compareUnicodeCodePoints( + compositeKey([left.class_name, left.selector]), + compositeKey([right.class_name, right.selector]), + ), ); const swift = swiftSymbols.length > 0; diff --git a/src/domain/propertyListKeys.test.ts b/src/domain/propertyListKeys.test.ts index e15fcb27e..15eb1bd6d 100644 --- a/src/domain/propertyListKeys.test.ts +++ b/src/domain/propertyListKeys.test.ts @@ -1,10 +1,6 @@ import { expect, it } from "vitest"; -import { - omitPrototypeKeys, - omittedPrototypeKeysLimitation, - parseXmlPropertyList, -} from "./propertyListKeys.js"; +import { omitPrototypeKeys, parseXmlPropertyList } from "./propertyListKeys.js"; const plist = (body: string) => `${body}`; @@ -67,7 +63,4 @@ it("omits own __proto__ entries that JSON decoding creates", () => { value: { a: [{ b: 3 }] }, omittedPrototypeKeys: 2, }); - expect(omittedPrototypeKeysLimitation(1)).toBe( - "1 dictionary entry keyed __proto__ was omitted because REA results cannot represent that key.", - ); }); diff --git a/src/domain/reconstructionCoverage.ts b/src/domain/reconstructionCoverage.ts index 1f7d6a318..485b66a5a 100644 --- a/src/domain/reconstructionCoverage.ts +++ b/src/domain/reconstructionCoverage.ts @@ -3,7 +3,10 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; -import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "./unicodeCodePointOrder.js"; import { evidenceBundleSchema, parseEvidenceBundle } from "./evidenceBundle.js"; import { @@ -405,8 +408,10 @@ const closureStatus = ( }; const reasonOrder = (left: ClosureReason, right: ClosureReason): number => - compareUnicodeCodePoints(left.code, right.code) || - compareUnicodeCodePoints(left.subject_id, right.subject_id); + compareUnicodeCodePoints( + compositeKey([left.code, left.subject_id]), + compositeKey([right.code, right.subject_id]), + ); const digest = (value: unknown): string => { const encoded = canonicalize(value); diff --git a/src/domain/reconstructionUnknowns.ts b/src/domain/reconstructionUnknowns.ts index c43330215..d05f96fe9 100644 --- a/src/domain/reconstructionUnknowns.ts +++ b/src/domain/reconstructionUnknowns.ts @@ -1,5 +1,8 @@ import { uniqueSorted } from "./canonicalOrdering.js"; -import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "./unicodeCodePointOrder.js"; import type { ReconstructionClaim, ReconstructionClaimResult, @@ -90,7 +93,7 @@ export const reconstructionProbes = ( const probes = unknowns.flatMap(({ recommended_probes: items }) => items); const candidates = probes.length > 0 ? probes : [defaultProbe(result.kind)]; for (const probe of candidates) { - const key = `${probe.operation}\0${probe.rationale}`; + const key = compositeKey([probe.operation, probe.rationale]); const current = output.get(key) ?? { ...probe, claim_ids: [], @@ -104,10 +107,11 @@ export const reconstructionProbes = ( output.set(key, current); } } - const sorted = [...output.values()].sort( - (left, right) => - compareUnicodeCodePoints(left.operation, right.operation) || - compareUnicodeCodePoints(left.rationale, right.rationale), + const sorted = [...output.values()].sort((left, right) => + compareUnicodeCodePoints( + compositeKey([left.operation, left.rationale]), + compositeKey([right.operation, right.rationale]), + ), ); return sorted; }; diff --git a/src/domain/referenceSourceImportParsing.test.ts b/src/domain/referenceSourceImportParsing.test.ts deleted file mode 100644 index 27595155b..000000000 --- a/src/domain/referenceSourceImportParsing.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { parseReferenceSourceImports } from "./referenceSourceImportParsing.js"; - -const parse = (source: string) => - parseReferenceSourceImports( - "main.ts", - new TextEncoder().encode(source), - "TypeScript", - ); - -describe("historical source dynamic imports", () => { - it.each([ - 'import("./lazy.js");', - 'const module = import("./lazy.js");', - 'async function load() { return await import("./lazy.js"); }', - 'import("./lazy.js", { with: { type: "json" } });', - ])("retains the literal dependency in %s", (source) => { - expect(parse(source)).toEqual({ - relationships: [ - { - from_path: "main.ts", - to: "./lazy.js", - kind: "imports", - resolution: "internal", - parse_state: "parsed", - }, - ], - parse_failures: [], - }); - }); - - it.each([ - "import(moduleName);", - "async function load(name: string) { return await import(name); }", - "import(`./${moduleName}.js`);", - ])("keeps a computed dependency unknown in %s", (source) => { - expect(parse(source)).toEqual({ - relationships: [ - { - from_path: "main.ts", - to: "", - kind: "imports", - resolution: "unknown", - parse_state: "partial", - }, - ], - parse_failures: [], - }); - }); - - it("retains static import and require relationships alongside dynamic imports", () => { - const result = parse( - 'import "./static.js"; require("./common.cjs"); import("node:fs");', - ); - expect(result.parse_failures).toEqual([]); - expect(result.relationships).toEqual([ - { - from_path: "main.ts", - to: "./static.js", - kind: "imports", - resolution: "internal", - parse_state: "parsed", - }, - { - from_path: "main.ts", - to: "./common.cjs", - kind: "requires", - resolution: "internal", - parse_state: "parsed", - }, - { - from_path: "main.ts", - to: "node:fs", - kind: "imports", - resolution: "external", - parse_state: "parsed", - }, - ]); - }); -}); diff --git a/src/domain/referenceSourceImportParsing.ts b/src/domain/referenceSourceImportParsing.ts index 3e0832ee4..e89707257 100644 --- a/src/domain/referenceSourceImportParsing.ts +++ b/src/domain/referenceSourceImportParsing.ts @@ -1,4 +1,4 @@ -import { parse, type ParserPlugin } from "@babel/parser"; +import { parse } from "@babel/parser"; import type { CallExpression, File, @@ -7,6 +7,7 @@ import type { StringLiteral, } from "@babel/types"; import { traverseJavaScriptAst } from "./javascript/javascriptSemanticTraversal.js"; +import { parserPluginsForPath } from "./javascript/javascriptSourceParser.js"; import { isCallExpression, isExportAllDeclaration, @@ -206,6 +207,9 @@ const extractRequireAndDynamicImports = ( from_path: string, relationships: ReferenceSourceImportRelationship[], ): void => { + // Single traversal owner: iterative, VISITOR_KEYS-gated, no recursion over + // loc/comment objects. Survives deeply nested generated member chains that + // overflowed the previous hand-rolled Object.values walker. const expressions: Array = []; for (const statement of body) traverseJavaScriptAst(statement, { @@ -263,18 +267,11 @@ const parseWithBabel = ( ast: File | undefined; reasons: readonly string[]; } => { - const plugins: ParserPlugin[] = ["jsx"]; - if (language === "TypeScript" || language === "TSX") { - plugins.push([ - "typescript", - { - dts: - path.endsWith(".d.ts") || - path.endsWith(".d.mts") || - path.endsWith(".d.cts"), - }, - ]); - } + // Single parser-mode owner: path-driven plugins (dts/JSX/mts) shared with + // the semantic pipeline. `language` only gates non-JS/TS callers upstream; + // TypeScript syntax must parse identically here and in semantic analysis. + void language; + const plugins = parserPluginsForPath(path); try { const ast = parse(source, { diff --git a/src/domain/referenceSourceImportRecovery.test.ts b/src/domain/referenceSourceImportRecovery.test.ts deleted file mode 100644 index e32973f59..000000000 --- a/src/domain/referenceSourceImportRecovery.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { parseReferenceSourceImports } from "./referenceSourceImportParsing.js"; - -const recoverySource = [ - "const missing;", - "let duplicate;", - "let duplicate;", - "let duplicate;", -].join("\n"); - -const recoveryReasons = [ - "Missing initializer in const declaration. (1:13)", - "Identifier 'duplicate' has already been declared. (3:4)", - "Identifier 'duplicate' has already been declared. (4:4)", -]; - -const moduleSource = [ - 'import "./static.js";', - 'export { value } from "./named.js";', - 'export * from "./all.js";', - 'require("./common.cjs");', - 'require.resolve("node:fs");', - 'import("./lazy.js");', - "import(moduleName);", -].join("\n"); - -const moduleRelationships = [ - ["./static.js", "imports", "internal", "parsed"], - ["./named.js", "imports", "internal", "parsed"], - ["./all.js", "imports", "internal", "parsed"], - ["./common.cjs", "requires", "internal", "parsed"], - ["node:fs", "requires", "external", "parsed"], - ["./lazy.js", "imports", "internal", "parsed"], - ["", "imports", "unknown", "partial"], -].map(([to, kind, resolution, parse_state]) => ({ - to, - kind, - resolution, - parse_state, -})); - -const parseSource = (path: string, source: string, language: string | null) => - parseReferenceSourceImports(path, new TextEncoder().encode(source), language); - -describe.each([ - ["main.js", "JavaScript"], - ["main.jsx", "JSX"], - ["main.ts", "TypeScript"], - ["main.tsx", "TSX"], -])("recovered reference imports in %s", (path, language) => { - it("retains every diagnostic and marks recovered relationships partial", () => { - const result = parseSource( - path, - `${recoverySource}\n${moduleSource}`, - language, - ); - - expect(result.parse_failures).toEqual( - recoveryReasons.map((reason) => ({ path, parser: "babel", reason })), - ); - expect(result.relationships).toEqual( - moduleRelationships.map((relationship) => ({ - ...relationship, - from_path: path, - parse_state: "partial", - })), - ); - }); - - it("preserves valid and computed relationships without diagnostics", () => { - expect(parseSource(path, moduleSource, language)).toEqual({ - relationships: moduleRelationships.map((relationship) => ({ - ...relationship, - from_path: path, - })), - parse_failures: [], - }); - }); - - it("reports recovery diagnostics when there are no relationships", () => { - expect(parseSource(path, recoverySource, language)).toEqual({ - relationships: [], - parse_failures: recoveryReasons.map((reason) => ({ - path, - parser: "babel", - reason, - })), - }); - }); - - it("returns no relationships when parsing throws", () => { - expect( - parseSource(path, 'import "./before.js";\nconst = ;', language), - ).toEqual({ - relationships: [], - parse_failures: [ - { path, parser: "babel", reason: "Unexpected token (2:6)" }, - ], - }); - }); -}); - -it.each(["main.ts", "types.d.ts", "types.d.mts", "types.d.cts"])( - "marks recovered TypeScript declarations partial in %s", - (path) => { - const result = parseSource( - path, - [ - "let duplicate: number;", - "let duplicate: number;", - 'import dep = require("node:path");', - 'declare module "ambient-package" {}', - ].join("\n"), - "TypeScript", - ); - expect(result).toEqual({ - relationships: [ - { - from_path: path, - to: "node:path", - kind: "requires", - resolution: "external", - parse_state: "partial", - }, - { - from_path: path, - to: "ambient-package", - kind: "declares-module", - resolution: "unknown", - parse_state: "partial", - }, - ], - parse_failures: [ - { - path, - parser: "babel", - reason: "Identifier 'duplicate' has already been declared. (2:4)", - }, - ], - }); - }, -); - -it("keeps unsupported source languages outside Babel parsing", () => { - expect(parseSource("main.py", recoverySource, "Python")).toEqual({ - relationships: [], - parse_failures: [], - }); -}); diff --git a/src/domain/referenceSourceRequireMembers.test.ts b/src/domain/referenceSourceRequireMembers.test.ts deleted file mode 100644 index 1b01748aa..000000000 --- a/src/domain/referenceSourceRequireMembers.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { parseReferenceSourceImports } from "./referenceSourceImportParsing.js"; - -const parseRequire = (source: string) => - parseReferenceSourceImports( - "main.cjs", - new TextEncoder().encode(source), - "JavaScript", - ); - -const knownCallees = [ - "require", - "require.resolve", - 'require["resolve"]', - "require.main", - 'require["main"]', -]; - -describe("historical source require member names", () => { - it.each([ - ...knownCallees, - 'require[("resolve")]', - 'require["res\\u006flve"]', - ])( - "retains a literal dependency for %s beside computed members", - (callee) => { - expect( - parseRequire( - `require[resolve]("./ignored.js"); ${callee}("./dep.js");`, - ), - ).toEqual({ - relationships: [ - { - from_path: "main.cjs", - to: "./dep.js", - kind: "requires", - resolution: "internal", - parse_state: "parsed", - }, - ], - parse_failures: [], - }); - }, - ); - - it.each([ - 'require[resolve]("./dep.js");', - 'require[main]("./dep.js");', - 'const resolve = "toString"; require[resolve]("./dep.js");', - 'const main = "toString"; require[main]("./dep.js");', - 'const resolve = "resolve"; require[resolve]("./dep.js");', - 'const main = "main"; require[main]("./dep.js");', - 'const method = "resolve"; require[method]("./dep.js");', - 'require[`resolve`]("./dep.js");', - 'require["re" + "solve"]("./dep.js");', - ])("does not infer computed member values in %s", (source) => { - expect(parseRequire(source)).toEqual({ - relationships: [], - parse_failures: [], - }); - }); - - it.each([ - "require?.", - "require.resolve?.", - 'require["resolve"]?.', - "require.main?.", - 'require["main"]?.', - "require?.resolve", - 'require?.["resolve"]', - "require?.[resolve]", - "require?.main", - 'require?.["main"]', - "require?.[main]", - "(require?.resolve)", - "require.resolve.call", - "require.main.require", - "module.require", - "other.resolve", - "other.require", - "require.toString", - 'require["toString"]', - ])("leaves the unrecognized callee %s unchanged", (callee) => { - expect(parseRequire(`${callee}("./dep.js");`)).toEqual({ - relationships: [], - parse_failures: [], - }); - }); - - it.each(knownCallees)("does not guess unknown arguments to %s", (callee) => { - expect( - parseRequire( - [ - 'const target = "./dep.js";', - `${callee}(target);`, - `${callee}(\`./dep.js\`);`, - `${callee}(getTarget());`, - `${callee}();`, - ].join("\n"), - ), - ).toEqual({ relationships: [], parse_failures: [] }); - }); -}); diff --git a/src/domain/residualUnknown.ts b/src/domain/residualUnknown.ts index f85996c29..5741223ea 100644 --- a/src/domain/residualUnknown.ts +++ b/src/domain/residualUnknown.ts @@ -2,7 +2,10 @@ import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; -import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "./unicodeCodePointOrder.js"; import { prefixedDigestSchema } from "./../domain/digests.js"; const evidenceIdSchema = prefixedDigestSchema("ev"); @@ -293,8 +296,9 @@ const sortedUnique = (values: readonly string[]): string[] => const sortedRelationships = ( values: readonly z.infer[], ): z.infer[] => - [...values].sort( - (left, right) => - compareUnicodeCodePoints(left.type, right.type) || - compareUnicodeCodePoints(left.unknown_id, right.unknown_id), + [...values].sort((left, right) => + compareUnicodeCodePoints( + compositeKey([left.type, left.unknown_id]), + compositeKey([right.type, right.unknown_id]), + ), ); diff --git a/src/domain/safeJson.test.ts b/src/domain/safeJson.test.ts deleted file mode 100644 index cb8c88d1a..000000000 --- a/src/domain/safeJson.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, it } from "vitest"; - -import { safeParseJson } from "./safeJson.js"; - -it("keeps the original JSON parse failure as the cause", () => { - const parsed = safeParseJson("{"); - - if (parsed.ok) throw new Error("expected invalid JSON to fail"); - expect(parsed.error).toContain("JSON"); - expect(parsed.cause).toBeInstanceOf(SyntaxError); -}); diff --git a/src/domain/symbolAnalysis.test.ts b/src/domain/symbolAnalysis.test.ts index 8ebb7b762..c43bbfb76 100644 --- a/src/domain/symbolAnalysis.test.ts +++ b/src/domain/symbolAnalysis.test.ts @@ -1,160 +1,9 @@ import { describe, expect, it } from "vitest"; -import { - categorizeSwiftTypes, - discoverObjcClasses, - discoverObjcProtocols, -} from "./symbolAnalysis.js"; - -describe("symbol analysis", () => { - it("deduplicates Objective-C classes and protocols by symbol name", () => { - const names = [ - { address: "0x1", name: "_OBJC_CLASS_$_App" }, - { address: "0x2", name: "_OBJC_CLASS_$_App" }, - { address: "0x3", name: "_OBJC_PROTOCOL_$_Delegate" }, - { address: "0x4", name: "__OBJC_PROTOCOL_REFERENCE_$_Delegate" }, - { address: "0x4", name: "_OBJC_PROTOCOL_$_Delegate" }, - ]; - expect(discoverObjcClasses(names, "App")).toMatchObject({ count: 1 }); - expect(discoverObjcProtocols(names)).toMatchObject({ count: 1 }); - }); - - it("excludes Objective-C ivars, metaclasses, properties, and protocols from classes", () => { - const result = discoverObjcClasses( - [ - { address: "0x1", name: "_OBJC_IVAR_$_Fixture.value" }, - { address: "0x2", name: "_OBJC_METACLASS_$_Fixture" }, - { address: "0x3", name: "_OBJC_PROP_$_Fixture.value" }, - { address: "0x4", name: "_OBJC_PROTOCOL_$_FixtureProtocol" }, - { address: "0x5", name: "_OBJC_CLASS_$_Fixture" }, - ], - "", - ); - - expect(result).toMatchObject({ - count: 1, - classes: [{ address: "0x5", name: "_OBJC_CLASS_$_Fixture" }], - }); - }); - - it("recognizes fragile Apple Objective-C class records without alias duplication", () => { - // Apple clang -target i386-apple-macosx10.5 - // -fobjc-runtime=macosx-fragile-10.5 emits these local class records. - // The `.objc_class_name_*` absolute symbols alias the same class and are - // deliberately not selected. - const names = [ - { address: "0x1ac", name: "l_OBJC_CLASS_ProbeClass" }, - { address: "0x0", name: ".objc_class_name_ProbeClass" }, - // A class named `NAME_` produces this exact legacy local symbol. - { address: "0x0", name: "l_OBJC_CLASS_NAME_" }, - ]; - expect(discoverObjcClasses(names, "")).toEqual({ - count: 2, - classes: [ - { address: "0x1ac", name: "l_OBJC_CLASS_ProbeClass" }, - { address: "0x0", name: "l_OBJC_CLASS_NAME_" }, - ], - }); - }); - - it("discovers modern Swift protocol descriptors without treating methods as declarations", () => { - // Current swiftc emits `…Mp` descriptors without the nominal `P` marker. - const names = [ - { address: "0xf0", name: "_$s4main7ScoringMp" }, - { address: "0x100", name: "_$s4main7ScoringTL" }, - { address: "0x110", name: "_$s4main7ScoringP5scoreSiyFTq" }, - ]; - expect(discoverObjcProtocols(names)).toEqual({ - count: 1, - protocols: [{ address: "0xf0", name: "_$s4main7ScoringMp" }], - }); - }); - - it("categorizes every Swift mangling family and deduplicates names", () => { - const result = categorizeSwiftTypes([ - { address: "1", name: "_TtCClass" }, - { address: "2", name: "_TtVStruct" }, - { address: "3", name: "_TtOEnum" }, - { address: "4", name: "_TtPProtocol" }, - { address: "5", name: "_TtEExtension" }, - { address: "6", name: "prefix_TtOther" }, - { address: "7", name: "_TtCClass" }, - ]); - expect(result).toMatchObject({ - total: 6, - categories: { - classes: { count: 1 }, - structs: { count: 1 }, - enums: { count: 1 }, - protocols: { count: 1 }, - extensions: { count: 1 }, - other: { count: 1 }, - }, - }); - }); - - it("filters Swift categories by a case-sensitive literal name", () => { - const result = categorizeSwiftTypes( - [ - { address: "0x1", name: "_TtCAccount" }, - { address: "0x2", name: "_TtCSession" }, - { address: "0x3", name: "_TtVAccountState" }, - ], - { category: "classes", pattern: "Account" }, - ); - - expect(result).toMatchObject({ - total: 1, - categories: { - classes: { - count: 1, - items: [{ address: "0x1", name: "_TtCAccount" }], - }, - structs: { count: 0, items: [] }, - }, - }); - }); - - it("classifies modern Swift manglings reported by current providers", () => { - const result = categorizeSwiftTypes([ - { address: "0x1000009f8", name: "$s4main4PairVMa" }, - { address: "0x100000ac4", name: "$s4main6ScorerVMa" }, - { address: "0x100000ab4", name: "_$s4main4PairVMa" }, - { address: "0x1", name: "_TtCClass" }, - { address: "0x1000009f8", name: "$s4main4PairVMa" }, - ]); - - expect(result).toMatchObject({ - total: 4, - categories: { - classes: { count: 1 }, - structs: { - count: 3, - items: [ - { address: "0x1000009f8", name: "$s4main4PairVMa" }, - { address: "0x100000ac4", name: "$s4main6ScorerVMa" }, - { address: "0x100000ab4", name: "_$s4main4PairVMa" }, - ], - }, - }, - }); - }); - - it("keeps non-Swift procedure names out of the Swift inventory", () => { - const result = categorizeSwiftTypes([ - { address: "0x1", name: "printf" }, - { address: "0x2", name: "_OBJC_CLASS_$_App" }, - { address: "0x3", name: "std::vector::push_back" }, - ]); - - expect(result).toMatchObject({ total: 0 }); - }); -}); +import { categorizeSwiftTypes } from "./symbolAnalysis.js"; describe("modern Swift category evidence", () => { it.each([ - ["$s4main4PairVMa", "structs"], - ["_$s4main6ScorerVMa", "structs"], ["$s4main7ServiceCMa", "classes"], ["$s4main5StateOMa", "enums"], ["$s4main7ScoringPMp", "protocols"], @@ -203,36 +52,6 @@ describe("modern Swift category evidence", () => { ).toMatchObject({ total: 0, unclassified: [] }); }); - it("joins Swift aliases only at the exact procedure address", () => { - const result = categorizeSwiftTypes( - [ - { address: "0x1", name: "main::Pair::typeMetadataAccessor" }, - { address: "0x2", name: "std::vector::push_back" }, - { address: "0x3", name: "main::Pair::other" }, - ], - { category: "structs", pattern: "Pair" }, - [ - { address: "0x1", name: "_$s4main4PairVMa" }, - { address: "0x4", name: "$s4main4PairVMa" }, - ], - ); - expect(result).toMatchObject({ - total: 1, - categories: { - structs: { - items: [ - { - address: "0x1", - name: "main::Pair::typeMetadataAccessor", - mangled_names: ["_$s4main4PairVMa"], - }, - ], - }, - }, - unclassified: [], - }); - }); - it("deduplicates display names after selecting a category", () => { expect( categorizeSwiftTypes( diff --git a/src/domain/symbolAnalysis.ts b/src/domain/symbolAnalysis.ts index 65e0fe8eb..6667afcc6 100644 --- a/src/domain/symbolAnalysis.ts +++ b/src/domain/symbolAnalysis.ts @@ -28,7 +28,8 @@ export const discoverObjcClasses = ( ({ name }) => name.includes(OBJC_CLASS_MARKER) || (name.startsWith(LEGACY_OBJC_CLASS_PREFIX) && - name.length > LEGACY_OBJC_CLASS_PREFIX.length), + name.length > LEGACY_OBJC_CLASS_PREFIX.length && + !/^l_OBJC_CLASS_NAME_(?:\.\d+)?$/u.test(name)), ) .filter(({ name }) => pattern.length === 0 || name.includes(pattern)), ); diff --git a/src/domain/unicodeCodePointOrder.ts b/src/domain/unicodeCodePointOrder.ts index 163039364..4f635048d 100644 --- a/src/domain/unicodeCodePointOrder.ts +++ b/src/domain/unicodeCodePointOrder.ts @@ -16,3 +16,11 @@ export const compareUnicodeCodePoints = ( if (leftIndex === left.length && rightIndex === right.length) return 0; return leftIndex === left.length ? -1 : 1; }; + +/** + * Collision-free composite key for deduplication/sorting. `\0`-joins + * collide when any component contains NUL (valid in JS property names); + * a JSON tuple escapes every component. Single owner for composite keys. + */ +export const compositeKey = (parts: readonly unknown[]): string => + JSON.stringify(parts); diff --git a/src/domain/webBundleAnalyzerInspection.ts b/src/domain/webBundleAnalyzerInspection.ts index 157345c94..daf3a2292 100644 --- a/src/domain/webBundleAnalyzerInspection.ts +++ b/src/domain/webBundleAnalyzerInspection.ts @@ -2,6 +2,7 @@ import { parse } from "@babel/parser"; import * as t from "@babel/types"; import { sanitizeEndpointCandidate } from "./browserObservation.js"; +import { compositeKey } from "./unicodeCodePointOrder.js"; import type { WebPageInspection } from "./browserObservationSchemas.js"; import type { WebBundleAnalysis } from "./webBundleAnalysis.js"; import { traverseJavaScriptAst } from "./javascript/javascriptSemanticTraversal.js"; @@ -271,7 +272,14 @@ const addWebMcpDeclaration = ( : [], ) : []; - const key = `webmcp\0${script.script_key}\0${name ?? ""}\0${schemaPropertyNames.join("\0")}`; + // Property names are a variable-length source-derived list: NUL-joins + // would collapse ["a\0b"] with ["a", "b"] and drop a declaration. + const key = compositeKey([ + "webmcp", + script.script_key, + name ?? "", + schemaPropertyNames, + ]); addUnique(accumulator, key, () => accumulator.webMcp.push({ name: name ?? null, diff --git a/src/domain/webInventory.test.ts b/src/domain/webInventory.test.ts index 123a90da8..51a6b42e9 100644 --- a/src/domain/webInventory.test.ts +++ b/src/domain/webInventory.test.ts @@ -12,15 +12,6 @@ import { } from "./webContentArtifact.js"; describe("web content artifacts", () => { - it("binds UTF-8 content, size, and digest inline", () => { - const artifact = createWebTextArtifact( - "const marker = '😀';", - "text/javascript", - ); - expect(webTextArtifactSchema.parse(artifact)).toEqual(artifact); - expect(artifact.bytes).toBe(Buffer.byteLength(artifact.text)); - }); - it("rejects altered content that reuses an artifact digest", () => { const artifact = createWebTextArtifact("original", "text/javascript"); expect( @@ -83,7 +74,7 @@ describe("stable web inventory", () => { content_size: 1_024, }, ]; - const forward = stableWebResources(inputs); + const forward = stableWebResources([...inputs, ...inputs.slice(0, 1)]); const reverse = stableWebResources([...inputs].reverse()); expect(reverse).toEqual(forward); @@ -117,20 +108,6 @@ describe("stable web inventory", () => { }); }); - it("deduplicates identical resource observations by stable identity", () => { - const duplicate = { - url: script.url, - origin: "https://app.example.test", - type: "Script", - mime_type: "text/javascript", - content_size: 1_024, - }; - - expect(stableWebResources([duplicate, duplicate])).toEqual( - stableWebResources([duplicate]), - ); - }); - it("reconciles raw URLs independently of stable inventory sort order", () => { const app = { url: script.url, diff --git a/src/domain/webRuntime.test.ts b/src/domain/webRuntime.test.ts deleted file mode 100644 index 9879256f0..000000000 --- a/src/domain/webRuntime.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { z } from "zod"; - -import { - webRuntimeLocationSchema, - webRuntimeSourceSchema, -} from "./webRuntime.js"; - -const properties = (schema: z.ZodType) => - z - .object({ properties: z.record(z.string(), z.unknown()) }) - .parse(z.toJSONSchema(schema, { io: "output" })).properties; - -describe("web runtime coordinate contract", () => { - it("advertises zero-based resource-relative CDP lines and UTF-16 columns", () => { - const location = properties(webRuntimeLocationSchema); - expect(location.line_number).toMatchObject({ - description: expect.stringContaining( - "Zero-based line in the resource named by url", - ), - }); - expect(location.script_id).toMatchObject({ - description: expect.stringContaining("no session-script association"), - }); - expect(location.column_number).toMatchObject({ - description: expect.stringContaining("Zero-based UTF-16 column"), - }); - const start = properties( - webRuntimeSourceSchema.shape.resource_start.unwrap(), - ); - expect(start.line_number).toMatchObject({ - description: expect.stringContaining( - "Zero-based line where the script text starts", - ), - }); - }); -}); diff --git a/src/domain/webScreenshot.test.ts b/src/domain/webScreenshot.test.ts deleted file mode 100644 index d62acaa7a..000000000 --- a/src/domain/webScreenshot.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - captureWebScreenshotInputSchema, - compareWebScreenshotsInputSchema, - createWebScreenshotArtifact, -} from "./webScreenshot.js"; - -describe("inline web screenshots", () => { - it("rejects removed screenshot size and pixel controls", () => { - expect( - captureWebScreenshotInputSchema.safeParse({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: "page-1", - maximum_image_bytes: 1, - }).success, - ).toBe(false); - - const artifact = createWebScreenshotArtifact(Buffer.from("image")); - expect( - compareWebScreenshotsInputSchema.safeParse({ - before: artifact, - after: artifact, - maximum_pixels: 1, - }).success, - ).toBe(false); - }); - - it("accepts a caller-supplied target ID without a length ceiling", () => { - const targetId = "target-".repeat(100); - expect( - captureWebScreenshotInputSchema.parse({ - cdp_endpoint: "http://127.0.0.1:9222", - allowed_origins: ["https://app.example.test"], - target_id: targetId, - }).target_id, - ).toBe(targetId); - }); -}); diff --git a/src/ghidra/GhidraLauncherEnvironment.test.ts b/src/ghidra/GhidraLauncherEnvironment.test.ts index 44008f2b7..f5d84880f 100644 --- a/src/ghidra/GhidraLauncherEnvironment.test.ts +++ b/src/ghidra/GhidraLauncherEnvironment.test.ts @@ -22,18 +22,6 @@ describe("Ghidra headless JVM environment", () => { }); }); - it.each(["linux", "darwin"] as const)( - "passes %s isolated JVM paths through direct argv instead of script options", - (platform) => { - expect( - ghidraHeadlessJavaOptions("/tmp/rea/home", "/tmp/rea/tmp", platform), - ).toEqual({ - JDK_JAVA_OPTIONS: "", - GHIDRA_HEADLESS_JAVA_OPTIONS: "", - }); - }, - ); - it.each(["%TEMP%", 'quote"', "amp&", "line\n", "nul\0"])( "rejects interpreter metacharacters in either Windows JVM path: %s", (suffix) => { diff --git a/src/ghidra/GhidraSessionRoot.test.ts b/src/ghidra/GhidraSessionRoot.test.ts index c1c1ecf60..fbfbccb6c 100644 --- a/src/ghidra/GhidraSessionRoot.test.ts +++ b/src/ghidra/GhidraSessionRoot.test.ts @@ -3,9 +3,6 @@ import { describe, expect, it } from "vitest"; import { ghidraSessionRoot } from "./GhidraSessionRoot.js"; -const hasDotPrefixElement = (directory: string): boolean => - directory.split(sep).some((element) => element.startsWith(".")); - const POSIX = process.platform !== "win32"; const posixFallback = join(resolve(sep), "tmp"); const posixBase = (...segments: string[]) => join(resolve(sep), ...segments); @@ -28,13 +25,6 @@ describe("ghidraSessionRoot", () => { ); }); - it("relocates a base that is itself a hidden directory", () => { - const base = posixBase("home", "operator", ".tmp"); - expect(ghidraSessionRoot({ base, fallback: posixBase("var", "tmp") })).toBe( - posixBase("var", "tmp"), - ); - }); - it("ignores a fallback that is itself dotted", () => { const base = posixBase("home", "operator", ".cache", "scratch"); expect( @@ -45,14 +35,6 @@ describe("ghidraSessionRoot", () => { ).toBe(posixBase("home", "operator")); }); - it("never returns a path with a dot-prefixed element", () => { - const directory = ghidraSessionRoot({ - base: posixBase("home", "operator", ".cache", "scratch"), - fallback: posixBase("home", "operator", ".cache"), - }); - expect(hasDotPrefixElement(directory)).toBe(false); - }); - it("uses the nearest safe ancestor when the platform has no fallback", () => { expect( ghidraSessionRoot({ diff --git a/tests/boundary/cli/nativePlistCli.test.ts b/tests/boundary/cli/nativePlistCli.test.ts index 487a9b1e1..50ed030f3 100644 --- a/tests/boundary/cli/nativePlistCli.test.ts +++ b/tests/boundary/cli/nativePlistCli.test.ts @@ -84,6 +84,11 @@ describe.skipIf(process.platform !== "darwin")( "BlobAAEC", "Built2020-01-01T00:00:00Z", "Rationan", + "Nested", + "Ratio0.5", + "Unbounded-infinity", + "empty key", + "", "", ].join(""), ); @@ -113,6 +118,13 @@ describe.skipIf(process.platform !== "darwin")( iso8601: "2020-01-01T00:00:00.000Z", }, Ratio: { $plist_type: "real", value: null }, + Nested: [ + { + Ratio: 0.5, + Unbounded: { $plist_type: "real", value: null }, + "": "empty key", + }, + ], }, bundle: { identifier: "com.example.types", executable: "App" }, provenance: [ @@ -122,7 +134,7 @@ describe.skipIf(process.platform !== "darwin")( ], limitations: [ expect.stringContaining("XML conversion"), - expect.stringContaining("1 non-finite real"), + expect.stringContaining("2 non-finite real"), ], }, }); diff --git a/tests/boundary/filesystem/dosComTarget.test.ts b/tests/boundary/filesystem/dosComTarget.test.ts index 7bd3eae7b..5968c769c 100644 --- a/tests/boundary/filesystem/dosComTarget.test.ts +++ b/tests/boundary/filesystem/dosComTarget.test.ts @@ -43,6 +43,24 @@ describe("DOS COM admission", () => { }), ).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } }); }); + it.each([1, 0xff00])("admits the actual file extent %i", async (length) => { + const directory = await createTestTempDirectory("rea-com-target-"); + const path = join(directory, "fixture.com"); + const bytes = Buffer.alloc(length, 0xc3); + await writeFile(path, bytes); + const target = await parseBinaryTarget(path, { + cwd: directory, + hostArchitecture: "x64", + formatHint: "dos-com", + }); + if (!target.ok) throw target.error; + expect(target.value).toMatchObject({ + format: "dos-com", + architecture: "x86", + sha256: createHash("sha256").update(bytes).digest("hex"), + }); + expect(await readFile(path)).toEqual(bytes); + }); it("rejects contradictory target kind", async () => { const directory = await createTestTempDirectory("rea-com-target-"); const path = join(directory, "fixture.com"); diff --git a/tests/boundary/filesystem/referenceSourceComputedRequire.test.ts b/tests/boundary/filesystem/referenceSourceComputedRequire.test.ts index 8f6695f6b..c478e6391 100644 --- a/tests/boundary/filesystem/referenceSourceComputedRequire.test.ts +++ b/tests/boundary/filesystem/referenceSourceComputedRequire.test.ts @@ -11,7 +11,48 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; it("distinguishes computed require member values from literal members in source evidence", async () => { const root = await createTestTempDirectory("rea-reference-require-members-"); - const sources = { + const literalCallees = [ + "require", + "require.resolve", + 'require["resolve"]', + "require.main", + 'require["main"]', + 'require[("resolve")]', + 'require["res\\u006flve"]', + ]; + const ignoredSources = [ + 'require[resolve]("./dep.js");', + 'require[main]("./dep.js");', + 'const resolve = "toString"; require[resolve]("./dep.js");', + 'const main = "toString"; require[main]("./dep.js");', + 'const resolve = "resolve"; require[resolve]("./dep.js");', + 'const main = "main"; require[main]("./dep.js");', + 'const method = "resolve"; require[method]("./dep.js");', + 'require[`resolve`]("./dep.js");', + 'require["re" + "solve"]("./dep.js");', + ...[ + "require?.", + "require.resolve?.", + 'require["resolve"]?.', + "require.main?.", + 'require["main"]?.', + "require?.resolve", + 'require?.["resolve"]', + "require?.[resolve]", + "require?.main", + 'require?.["main"]', + "require?.[main]", + "(require?.resolve)", + "require.resolve.call", + "require.main.require", + "module.require", + "other.resolve", + "other.require", + "require.toString", + 'require["toString"]', + ].map((callee) => `${callee}("./dep.js");`), + ]; + const sources: Record = { "computed.cjs": [ 'const resolve = "toString";', 'const main = "toString";', @@ -21,15 +62,21 @@ it("distinguishes computed require member values from literal members in source ].join("\n"), "literal.cjs": 'console.log(require["resolve"]("./dep.js"));\n', "dep.js": 'throw new Error("The dependency must not execute");\n', + "ignored.cjs": ignoredSources.map((source) => `{ ${source} }`).join("\n"), "unknown.cjs": [ "function load(target) {", - " require(target);", - " require.resolve(target);", - ' require["resolve"](target);', + ...literalCallees.flatMap((callee) => [ + ` ${callee}(target);`, + ` ${callee}(\`./dep.js\`);`, + ` ${callee}(getTarget());`, + ` ${callee}();`, + ]), " return import(target);", "}", ].join("\n"), }; + for (const [index, callee] of literalCallees.entries()) + sources[`member-${index}.cjs`] = `${callee}("./dep.js");\n`; await Promise.all( Object.entries(sources).map(([path, source]) => writeFile(join(root, path), source), @@ -67,6 +114,13 @@ it("distinguishes computed require member values from literal members in source resolution: "internal", parse_state: "parsed", }, + ...literalCallees.map((_, index) => ({ + from_path: `member-${index}.cjs`, + to: "dep.js", + kind: "requires", + resolution: "internal", + parse_state: "parsed", + })), { from_path: "unknown.cjs", to: "", diff --git a/tests/boundary/filesystem/referenceSourceDynamicImports.test.ts b/tests/boundary/filesystem/referenceSourceDynamicImports.test.ts index e78a56f37..432b7bf30 100644 --- a/tests/boundary/filesystem/referenceSourceDynamicImports.test.ts +++ b/tests/boundary/filesystem/referenceSourceDynamicImports.test.ts @@ -17,6 +17,8 @@ it("resolves dynamic source imports while retaining computed targets as unknown" 'const lazy = import("./lazy");', 'async function load() { return await import("./data.json", { with: { type: "json" } }); }', 'const name = "./not-guessed.js"; import(name);', + "import(`./${name}.js`);", + 'import("node:fs");', ].join("\n"), ), ...["static.ts", "common.js", "lazy.ts"].map((path) => @@ -32,7 +34,7 @@ it("resolves dynamic source imports while retaining computed targets as unknown" }); if (!result.ok) throw result.error; expect(result.value.parse_failures).toEqual([]); - expect(result.value.relationships).toHaveLength(5); + expect(result.value.relationships).toHaveLength(6); for (const [to, kind] of [ ["static.ts", "imports"], ["common.js", "requires"], @@ -53,4 +55,11 @@ it("resolves dynamic source imports while retaining computed targets as unknown" resolution: "unknown", parse_state: "partial", }); + expect(result.value.relationships).toContainEqual({ + from_path: "main.ts", + to: "node:fs", + kind: "imports", + resolution: "external", + parse_state: "parsed", + }); }); diff --git a/tests/boundary/filesystem/referenceSourceRecovery.test.ts b/tests/boundary/filesystem/referenceSourceRecovery.test.ts index 53585d865..5b9f6ad45 100644 --- a/tests/boundary/filesystem/referenceSourceRecovery.test.ts +++ b/tests/boundary/filesystem/referenceSourceRecovery.test.ts @@ -11,27 +11,37 @@ import { import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +const sources = { + "fatal.js": 'import "./valid";\nconst = ;', + "ignored.py": 'import "./valid"; const missing;\n', + "lazy.js": "export const lazy = true;\n", + "recovered.d.cts": [ + "let duplicate: number;", + "let duplicate: number;", + 'import dep = require("./valid");', + 'declare module "ambient-package" {}', + ].join("\n"), + "recovered.js": [ + "const missing;", + "let duplicate;", + "let duplicate;", + "let duplicate;", + 'import "./valid";', + 'require("node:fs");', + 'import("./lazy");', + "import(moduleName);", + ].join("\n"), + "recovered.ts": [ + "let duplicate: number;", + "let duplicate: number;", + 'import dep = require("./valid");', + 'declare module "ambient-package" {}', + ].join("\n"), + "valid.js": + 'export { readFile } from "node:fs"; export * from "node:path";\n', +}; it("preserves recovered diagnostics and file evidence through filesystem import", async () => { const root = await createTestTempDirectory("rea-reference-recovery-"); - const sources = { - "fatal.js": 'import "./valid";\nconst = ;', - "recovered.js": [ - "const missing;", - "let duplicate;", - "let duplicate;", - "let duplicate;", - 'import "./valid";', - 'require("node:fs");', - "import(moduleName);", - ].join("\n"), - "recovered.ts": [ - "let duplicate: number;", - "let duplicate: number;", - 'import dep = require("./valid");', - 'declare module "ambient-package" {}', - ].join("\n"), - "valid.js": 'export * from "node:path";\n', - }; await mkdir(join(root, "src")); await Promise.all( Object.entries(sources).map(([path, source]) => @@ -66,6 +76,11 @@ it("preserves recovered diagnostics and file evidence through filesystem import" const failures = [ { path: "src/fatal.js", parser: "babel", reason: "Unexpected token (2:6)" }, + { + path: "src/recovered.d.cts", + parser: "babel", + reason: "Identifier 'duplicate' has already been declared. (2:4)", + }, { path: "src/recovered.js", parser: "babel", @@ -94,6 +109,20 @@ it("preserves recovered diagnostics and file evidence through filesystem import" ), ).toEqual(failures); expect(graph.relationships).toEqual([ + { + from_path: "src/recovered.d.cts", + to: "ambient-package", + kind: "declares-module", + resolution: "unknown", + parse_state: "partial", + }, + { + from_path: "src/recovered.d.cts", + to: "src/valid.js", + kind: "requires", + resolution: "internal", + parse_state: "partial", + }, { from_path: "src/recovered.js", to: "", @@ -108,6 +137,13 @@ it("preserves recovered diagnostics and file evidence through filesystem import" resolution: "external", parse_state: "partial", }, + { + from_path: "src/recovered.js", + to: "src/lazy.js", + kind: "imports", + resolution: "internal", + parse_state: "partial", + }, { from_path: "src/recovered.js", to: "src/valid.js", @@ -129,6 +165,13 @@ it("preserves recovered diagnostics and file evidence through filesystem import" resolution: "internal", parse_state: "partial", }, + { + from_path: "src/valid.js", + to: "node:fs", + kind: "imports", + resolution: "external", + parse_state: "parsed", + }, { from_path: "src/valid.js", to: "node:path", diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts index 661f33634..1666e129f 100644 --- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts +++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts @@ -20,37 +20,69 @@ import { observed as ok } from "../../fixtures/analysisExecution.js"; afterEach(closeEnhancedToolResources); -describe("enhanced MCP tools", () => { - it("discovers every Objective-C class from one complete inventory", async () => { - const client = await connect({ - execute: (name) => { - expect(name).toBe("list_names"); - return Promise.resolve( - ok([ - // Apple clang modern Objective-C ABI `nm` output: the first row - // is a class definition; the remaining rows are method metadata, - // class_ro_t, and a class reference. - { address: "0x70", value: "_OBJC_CLASS_$_ProbeClass" }, - { address: "0x1a8", value: "__OBJC_$_CLASS_METHODS_ProbeClass" }, - { address: "0x230", value: "__OBJC_CLASS_RO_$_ProbeClass" }, - { address: "0x450", value: "_OBJC_CLASSLIST_REFERENCES_$_" }, - { - address: "0x298", - value: "__OBJC_$_CATEGORY_CLASS_METHODS_ProbeClass_$_Category", - }, - ]), - ); - }, - }); - const result = jsonResult( - await client.callTool({ name: "get_objc_classes", arguments: {} }), - ); - expect(result).toEqual({ - count: 1, - classes: [{ address: "0x70", name: "_OBJC_CLASS_$_ProbeClass" }], - }); +it("discovers declarations without counting duplicates or compiler bookkeeping", async () => { + const client = await connect({ + execute: (name) => { + expect(name).toBe("list_names"); + return Promise.resolve( + ok([ + { address: "0x1", value: "_OBJC_CLASS_$_First" }, + { address: "0x2", value: "_OBJC_CLASS_$_Last" }, + { address: "0x3", value: "_OBJC_CLASS_$_First" }, + { address: "0x4", value: "__OBJC_CLASS_RO_$_First" }, + { address: "0x5", value: "_OBJC_CLASSLIST_REFERENCES_$_" }, + { address: "0x6", value: "l_OBJC_CLASS_NAME_" }, + { address: "0x7", value: "_OBJC_IVAR_$_First.value" }, + { address: "0x8", value: "_OBJC_METACLASS_$_First" }, + { address: "0x9", value: "_OBJC_PROP_$_First.value" }, + { address: "0xa", value: "__OBJC_PROTOCOL_$_Delegate" }, + { address: "0xb", value: "__OBJC_PROTOCOL_$_Delegate" }, + { address: "0xc", value: "__OBJC_PROTOCOL_REFERENCE_$_Delegate" }, + { address: "0xd", value: "_$s4main7ScoringMp" }, + { address: "0xe", value: "_$s4main7ScoringTL" }, + { address: "0xf", value: "_$s4main7ScoringP5scoreSiyFTq" }, + { address: "0x10", value: "l_OBJC_CLASS_Legacy" }, + { address: "0x11", value: "l_OBJC_CLASS_NAME_.1" }, + ]), + ); + }, }); + const result = jsonResult( + await client.callTool({ name: "get_objc_classes", arguments: {} }), + ); + expect(result).toMatchObject({ + count: 3, + classes: [ + { address: "0x1", name: "_OBJC_CLASS_$_First" }, + { address: "0x2", name: "_OBJC_CLASS_$_Last" }, + { address: "0x10", name: "l_OBJC_CLASS_Legacy" }, + ], + }); + expect( + jsonResult( + await client.callTool({ + name: "get_objc_classes", + arguments: { pattern: "First" }, + }), + ), + ).toMatchObject({ + count: 1, + classes: [{ address: "0x1", name: "_OBJC_CLASS_$_First" }], + }); + expect( + jsonResult( + await client.callTool({ name: "get_objc_protocols", arguments: {} }), + ), + ).toMatchObject({ + count: 2, + protocols: [ + { address: "0xa", name: "__OBJC_PROTOCOL_$_Delegate" }, + { address: "0xd", name: "_$s4main7ScoringMp" }, + ], + }); +}); +describe("enhanced MCP tools", () => { it("returns the complete overview inline with exhaustive totals", async () => { const client = await connect({ execute: (name) => { diff --git a/tests/boundary/mcp/enhancedTools.swiftTypes.test.ts b/tests/boundary/mcp/enhancedTools.swiftTypes.test.ts index 49d7268a5..128b9c281 100644 --- a/tests/boundary/mcp/enhancedTools.swiftTypes.test.ts +++ b/tests/boundary/mcp/enhancedTools.swiftTypes.test.ts @@ -36,7 +36,18 @@ describe("Swift classification through MCP", () => { arguments: test.arguments, }); expect(result.isError).not.toBe(true); - expect(jsonResult(result)).toMatchObject({ total: test.total }); + const inventory = jsonResult(result); + expect(inventory).toMatchObject({ total: test.total }); + if (test.arguments.pattern === undefined) + expect(inventory).toMatchObject({ + categories: { + structs: { + items: expect.not.arrayContaining([ + expect.objectContaining({ address: "0x100000c0c" }), + ]), + }, + }, + }); if (test.arguments.pattern === undefined) expect(jsonResult(result)).toMatchObject({ unclassified: [ diff --git a/tests/boundary/mcp/ghidraNativeApiMcp.test.ts b/tests/boundary/mcp/ghidraNativeApiMcp.test.ts index 18f77fdeb..b0fe73363 100644 --- a/tests/boundary/mcp/ghidraNativeApiMcp.test.ts +++ b/tests/boundary/mcp/ghidraNativeApiMcp.test.ts @@ -16,10 +16,14 @@ describe("Ghidra MCP native API evidence", () => { ).structuredContent, ); expect(inspection.normalized_result).toMatchObject({ + procedure: { address: "0x401000", name: "fixture_main" }, boundary: { available: true, + return_type: { data_type: "int", confidence: "medium" }, jump_tables: [ { + dispatch_address: "0x401010", + data_sources: [{ address: "0x403000" }], mappings: [{ case_value: 0, target_address: "0x401020" }], default_targets: [ { target_address: "0x401030", confidence: "high" }, @@ -27,6 +31,7 @@ describe("Ghidra MCP native API evidence", () => { }, ], }, + unsupported_branches: [], residual_unknowns: [], }); expect( diff --git a/tests/boundary/mcp/managedMcp.test.ts b/tests/boundary/mcp/managedMcp.test.ts index 6a985d7ec..43043152f 100644 --- a/tests/boundary/mcp/managedMcp.test.ts +++ b/tests/boundary/mcp/managedMcp.test.ts @@ -1,5 +1,6 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; +import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -385,13 +386,30 @@ const verifyImport = async ( operation: "import_managed_reconstruction", provider: { id: "rea-dotnet-workflows" }, confidence: "inferred", + authority: "analyst-inference", normalized_result: { + phase: "reconstruction-import", executed: false, + decompiler: { name: "ilspycmd", version: "9.1.0.7988", family: "ilspy" }, summary: { imported_methods: 1, decompiled_csharp_methods: 1 }, methods: [ { token: method.token, - validation: { canonical_observation: false }, + signature_sha256: method.signature.raw_sha256, + normalized_il_sha256: method.body.normalized_il_sha256, + reconstruction: { + kind: "decompiled-csharp", + language: "csharp", + text_sha256: createHash("sha256") + .update("internal static void Main() { }") + .digest("hex"), + }, + validation: { + matched_static_member: true, + exact_build_required: true, + canonical_observation: false, + confidence_floor: "inference", + }, }, ], }, diff --git a/tests/conformance/native/keyed-archive-uid-root.swift b/tests/conformance/native/keyed-archive-uid-root.swift index 743f2dec4..54a213a4d 100644 --- a/tests/conformance/native/keyed-archive-uid-root.swift +++ b/tests/conformance/native/keyed-archive-uid-root.swift @@ -1,7 +1,8 @@ import Foundation -// Encode the root under a key that matches the UID marker spelling. +// Encode roots under keys that match both binary and XML UID marker spellings. let archiver = NSKeyedArchiver(requiringSecureCoding: false) archiver.encode("payload" as NSString, forKey: "UID") +archiver.encode("payload" as NSString, forKey: "CF$UID") archiver.finishEncoding() try archiver.encodedData.write(to: URL(fileURLWithPath: CommandLine.arguments[1])) diff --git a/tests/fixtures/javascriptArtifactTypeScriptDialect.ts b/tests/fixtures/javascriptArtifactTypeScriptDialect.ts index f0677b175..f5dd81dcf 100644 --- a/tests/fixtures/javascriptArtifactTypeScriptDialect.ts +++ b/tests/fixtures/javascriptArtifactTypeScriptDialect.ts @@ -42,6 +42,11 @@ export const typeScriptDialectCases = [ kind: "static-import", source: 'const element =
;\nimport "./dep.js";', }, + { + path: "component.d.tsx", + kind: "static-import", + source: 'const element =
;\nimport "./dep.js";', + }, { path: "component.jsx", kind: "static-import", diff --git a/tests/process-global/updateMaintenance.test.ts b/tests/process-global/updateMaintenance.test.ts index bdda28912..760bd96aa 100644 --- a/tests/process-global/updateMaintenance.test.ts +++ b/tests/process-global/updateMaintenance.test.ts @@ -102,6 +102,8 @@ describe("OMP integration maintenance", () => { }); it("preserves Grok Build disabled_mcp_servers during maintenance planning", async () => { + // Strict identity: a user-disabled integration must never be selected + // for maintenance, even with a healthy owned entry underneath. const registration = `[mcp_servers.rea]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(entryPoint)}, "mcp"]\nstartup_timeout_sec = 30\n`; const configPath = await writeClient( "grok_build", From bf934d5592e707ba5e7769043de3a430ed8d4923 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:07:01 +0200 Subject: [PATCH 108/189] fix(hopper): probe interior navigation from multi-byte instructions (#1285) The real-Hopper navigation probe derived its interior coordinate as anchor + 1, which assumes the fixture procedure's first instruction is longer than one byte. Host toolchains without endbr64-style prologue padding (Kali gcc 16, or any build with -fcf-protection=none) compile rea_entry to start with the one-byte push rbp, so anchor + 1 is itself an instruction boundary: goto_address correctly observes that boundary and the boundary-contract run rejects a correct bridge. Advance the probe to the first instruction followed by a coordinate gap larger than one byte and derive the interior-coordinate assertions from that instruction, so the probed coordinate is never an analyzed-object boundary on either prologue encoding. --- scripts/lib/real-hopper-navigation.mjs | 27 ++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/scripts/lib/real-hopper-navigation.mjs b/scripts/lib/real-hopper-navigation.mjs index c4096d869..95353f795 100644 --- a/scripts/lib/real-hopper-navigation.mjs +++ b/scripts/lib/real-hopper-navigation.mjs @@ -91,14 +91,29 @@ async function verifyNavigation( ); assert.equal(coordinates[0], address); assert.ok(coordinates[1], "fixture omitted a second instruction"); - const interior = `0x${(BigInt(address) + 1n).toString(16)}`; - assert.equal(await call("goto_address", { address: interior }), address); - assert.equal(await call("current_address"), address); + // The host toolchain controls the prologue encoding: without endbr64-style + // padding the first instruction is one byte, so address + 1 is itself an + // instruction boundary. Probe from inside the first multi-byte instruction + // so the interior coordinate is never an analyzed-object boundary. + let anchor = 0; + while (anchor + 1 < coordinates.length) { + if (BigInt(coordinates[anchor + 1]) - BigInt(coordinates[anchor]) > 1n) + break; + anchor += 1; + } + assert.ok( + anchor + 1 < coordinates.length, + "fixture omitted a multi-byte instruction for interior navigation", + ); + const containing = coordinates[anchor]; + const interior = `0x${(BigInt(containing) + 1n).toString(16)}`; + assert.equal(await call("goto_address", { address: interior }), containing); + assert.equal(await call("current_address"), containing); assert.equal( await call("next_address", { address: interior }), - coordinates[1], + coordinates[anchor + 1], ); - assert.equal(await call("prev_address", { address: interior }), address); + assert.equal(await call("prev_address", { address: interior }), containing); for (const unmapped of ["0x0", "0xfffffffffffffffe"]) { for (const operation of ["goto_address", "next_address", "prev_address"]) await invalid( @@ -106,7 +121,7 @@ async function verifyNavigation( { address: unmapped }, /Address is outside every segment/u, ); - assert.equal(await call("current_address"), address); + assert.equal(await call("current_address"), containing); for (const operation of [ "set_address_name", "set_bookmark", From d79317cda0bbe8240eb7e25b0a5de90dcffca5fa Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:19:41 +0800 Subject: [PATCH 109/189] fix(artifacts): bind ASAR interpretation to owned snapshots Verify captured container bytes against their inventoried digest before listing or reading packed members. Isolate per-reader ASAR metadata, preserve original unpacked companions, and retain complete inventories when snapshot cleanup fails. --- src/artifacts/AsarArtifactReader.ts | 139 ++++++++++++++++-- src/artifacts/inventory/scanCanonical.ts | 40 +++-- src/artifacts/inventory/scanReader.ts | 21 +-- .../javascript/JavaScriptArtifactFiles.ts | 43 ++++-- .../filesystem/asarInventoryFreshness.test.ts | 119 ++++++++++++++- .../asarStreamingAllocation.test.ts | 35 +++-- .../javascriptArtifactContentIdentity.test.ts | 4 +- 7 files changed, 323 insertions(+), 78 deletions(-) diff --git a/src/artifacts/AsarArtifactReader.ts b/src/artifacts/AsarArtifactReader.ts index 02ebb1bbe..bedd9a5f2 100644 --- a/src/artifacts/AsarArtifactReader.ts +++ b/src/artifacts/AsarArtifactReader.ts @@ -1,7 +1,23 @@ -import { constants, createReadStream, type Stats } from "node:fs"; -import { lstat, open, realpath, type FileHandle } from "node:fs/promises"; +import { + constants, + createReadStream, + createWriteStream, + type ReadStream, + type Stats, +} from "node:fs"; +import { + lstat, + mkdtemp, + open, + realpath, + rm, + type FileHandle, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; import { isAbsolute, join, relative, sep } from "node:path"; -import { Readable } from "node:stream"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar"; @@ -24,24 +40,28 @@ export class AsarArtifactReader implements ArtifactReader { #archiveSize: number | undefined; #headerSize: number | undefined; readonly #entries = new Map(); + #snapshot: { readonly path: string; readonly sha256: string } | undefined; + #snapshotRoot: string | undefined; constructor( private readonly path: string, private readonly openUnpackedFile: OpenAsarUnpackedFile = open, + private readonly removeSnapshot: (path: string) => Promise = (path) => + rm(path, { recursive: true, force: true }), ) {} async *entries(signal?: AbortSignal): AsyncIterable { let paths: string[]; try { - // ASAR caches headers by path even after the archive has been replaced. + await this.prepareContainer(undefined, signal); + const snapshotPath = this.#snapshotPath(); this.#resetArchiveState(); this.#entries.clear(); - uncache(this.path); - paths = listPackage(this.path, { isPack: false }).sort((left, right) => + paths = listPackage(snapshotPath, { isPack: false }).sort((left, right) => left.localeCompare(right, "en"), ); - this.#headerSize = getRawHeader(this.path).headerSize; - const archiveMetadata = await lstat(this.path); + this.#headerSize = getRawHeader(snapshotPath).headerSize; + const archiveMetadata = await lstat(snapshotPath); if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink()) throw new ArtifactReaderFailure( "format", @@ -64,7 +84,7 @@ export class AsarArtifactReader implements ArtifactReader { : listed; let metadata: ReturnType; try { - metadata = statFile(this.path, providerPath, false); + metadata = statFile(this.#snapshotPath(), providerPath, false); } catch (cause: unknown) { throw asarFailure(this.path, `stat ${path}`, cause); } @@ -176,7 +196,7 @@ export class AsarArtifactReader implements ArtifactReader { let handle: FileHandle | undefined; try { const openedHandle = await open( - this.path, + this.#snapshotPath(), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, ); handle = openedHandle; @@ -210,17 +230,104 @@ export class AsarArtifactReader implements ArtifactReader { } } - /** Open raw container bytes to verify the inventory identity before analysis. */ - openContainer(signal?: AbortSignal): Readable { + /** Capture once per reader lifetime; bind all interpretation to these exact bytes. */ + async prepareContainer( + expectedSha256?: string, + signal?: AbortSignal, + ): Promise { abortIfNeeded(signal); - return createReadStream(this.path, signal === undefined ? {} : { signal }); + if (this.#snapshot === undefined && this.#snapshotRoot !== undefined) + await this.close(); + if (this.#snapshot === undefined) { + try { + this.#snapshotRoot = await mkdtemp( + join(tmpdir(), "rea-asar-snapshot-"), + ); + const snapshotPath = join(this.#snapshotRoot, "container.asar"); + const hash = createHash("sha256"); + const handle = await open( + this.path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + const source = handle.createReadStream(); + const digesting = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + hash.update(chunk); + callback(null, chunk); + }, + }); + await pipeline( + source, + digesting, + createWriteStream(snapshotPath, { flags: "wx", mode: 0o600 }), + signal === undefined ? {} : { signal }, + ); + this.#snapshot = { path: snapshotPath, sha256: hash.digest("hex") }; + } catch (cause: unknown) { + const primary = + signal?.aborted === true + ? new ArtifactReaderFailure( + "cancelled", + "ASAR operation cancelled", + { cause }, + ) + : asarFailure(this.path, "snapshot", cause); + try { + await this.close(); + } catch (cleanupCause: unknown) { + throw ArtifactReaderFailure.withCleanup( + primary, + ArtifactReaderFailure.cleanupObservation(cleanupCause, this.path), + ); + } + throw primary; + } + } + if ( + expectedSha256 !== undefined && + this.#snapshot.sha256 !== expectedSha256 + ) + throw new ArtifactReaderFailure( + "integrity", + `ASAR container changed before interpretation: ${this.path}`, + ); } - close(): Promise { - uncache(this.path); + /** Read the same captured container that supplies headers and packed members. */ + async openContainer(signal?: AbortSignal): Promise { + await this.prepareContainer(undefined, signal); + return createReadStream( + this.#snapshotPath(), + signal === undefined ? {} : { signal }, + ); + } + + async close(): Promise { + const root = this.#snapshotRoot; + if (root !== undefined) { + try { + await this.removeSnapshot(root); + } catch (cause: unknown) { + throw ArtifactReaderFailure.withCleanup(cause, { + reason: `Could not remove ASAR snapshot: ${root}`, + resources: [root], + }); + } + this.#snapshotRoot = undefined; + } + if (this.#snapshot !== undefined) uncache(this.#snapshot.path); + this.#snapshot = undefined; this.#resetArchiveState(); this.#entries.clear(); - return Promise.resolve(); + } + + #snapshotPath(): string { + if (this.#snapshot === undefined) + throw new ArtifactReaderFailure( + "integrity", + "ASAR snapshot is not available", + ); + return this.#snapshot.path; } provenance(): readonly [] { diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index ca1324e17..abd524693 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -1,6 +1,8 @@ import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; +import { AsarArtifactReader } from "../AsarArtifactReader.js"; + import { lstat } from "node:fs/promises"; import type { Stats } from "node:fs"; @@ -61,6 +63,7 @@ export const scanCanonicalArtifactInventory = async ( options.environment ?? {}, options.signal, ); + const ownedReaders: ArtifactReader[] = reader === undefined ? [] : [reader]; let outcome: | { readonly kind: "completed"; @@ -68,8 +71,11 @@ export const scanCanonicalArtifactInventory = async ( } | { readonly kind: "failed"; readonly cause: unknown }; try { + if (reader instanceof AsarArtifactReader) + await reader.prepareContainer(rootDigest?.sha256, options.signal); const { nodes, occurrences, pendingContradictions } = await scanReader( reader, + ownedReaders, options.signal, integrity, ); @@ -90,22 +96,26 @@ export const scanCanonicalArtifactInventory = async ( } catch (cause: unknown) { outcome = { kind: "failed", cause }; } - try { - await reader?.close(); - } catch (cleanupCause: unknown) { - const cleanup = ArtifactReaderFailure.cleanupObservation( - cleanupCause, - `artifact reader for ${path}`, - ); - const primary = outcome.kind === "failed" ? outcome.cause : cleanupCause; - throw ArtifactReaderFailure.withCleanup( - primary, - cleanup, - outcome.kind === "completed" - ? { kind: "artifact-inventory", inventory: outcome.snapshot } - : undefined, - ); + let cleanupFailure: ArtifactReaderFailure | undefined; + for (const owned of ownedReaders.reverse()) { + try { + await owned.close(); + } catch (cleanupCause: unknown) { + const cleanup = ArtifactReaderFailure.cleanupObservation( + cleanupCause, + `artifact reader for ${path}`, + ); + cleanupFailure = ArtifactReaderFailure.withCleanup( + cleanupFailure ?? + (outcome.kind === "failed" ? outcome.cause : cleanupCause), + cleanup, + outcome.kind === "completed" + ? { kind: "artifact-inventory", inventory: outcome.snapshot } + : undefined, + ); + } } + if (cleanupFailure !== undefined) throw cleanupFailure; if (outcome.kind === "failed") throw outcome.cause; return outcome.snapshot; }; diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 7de218b8a..1ee691a74 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -52,10 +52,12 @@ interface ScanContext { readonly occurrenceByPath: Map; readonly registry: ArtifactPathRegistry; readonly expandedContainerIds: Set; + readonly ownedReaders: ArtifactReader[]; } export const scanReader = async ( reader: ArtifactReader | undefined, + ownedReaders: ArtifactReader[], signal?: AbortSignal, integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY, ): Promise<{ @@ -76,6 +78,7 @@ export const scanReader = async ( occurrenceByPath: new Map(), registry: new ArtifactPathRegistry(), expandedContainerIds: new Set(), + ownedReaders, }; await visitArtifactEntries(context, reader, ""); // Archive directories may appear after their children. Resolve containment @@ -99,13 +102,11 @@ const visitArtifactEntries = async ( readonly reader: ArtifactReader; readonly prefix: string; readonly iterator: AsyncIterator; - readonly owned: boolean; }> = [ { reader: currentReader, prefix, iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](), - owned: false, }, ]; try { @@ -115,7 +116,6 @@ const visitArtifactEntries = async ( const next = await frame.iterator.next(); if (next.done) { stack.pop(); - if (frame.owned) await frame.reader.close(); continue; } const entry = next.value; @@ -164,27 +164,22 @@ const visitArtifactEntries = async ( } context.occurrences.push(occurrence); context.occurrenceByPath.set(logicalPath, occurrence); - if (expandableAsar && digested?.mismatched !== true) { + if (expandableAsar && digested !== undefined && !digested.mismatched) { const nested = new AsarArtifactReader(entry.adapterKey); + context.ownedReaders.push(nested); + await nested.prepareContainer(digested.node.sha256, context.signal); // Only traversed containers can own members, not opaque ASAR-named files. context.expandedContainerIds.add(occurrence.occurrence_id); stack.push({ reader: nested, prefix: logicalPath, iterator: nested.entries(context.signal)[Symbol.asyncIterator](), - owned: true, }); } } } finally { - await Promise.allSettled( - stack - .filter(({ owned }) => owned) - .map(async ({ reader, iterator }) => { - await iterator.return?.(); - await reader.close(); - }), - ); + // Readers remain owned by the inventory until its complete observation is built. + for (const { iterator } of stack) await iterator.return?.(); } }; diff --git a/src/artifacts/javascript/JavaScriptArtifactFiles.ts b/src/artifacts/javascript/JavaScriptArtifactFiles.ts index a6aa2600f..cfe1e811b 100644 --- a/src/artifacts/javascript/JavaScriptArtifactFiles.ts +++ b/src/artifacts/javascript/JavaScriptArtifactFiles.ts @@ -71,7 +71,7 @@ export const readJavaScriptArtifactFiles = async ( "Root artifact node is missing", ); await verifyEntryBytes( - reader.openContainer(signal), + await reader.openContainer(signal), { path: ".", sha256: root.sha256, bytes: root.size }, signal, ); @@ -114,16 +114,16 @@ const visitReader = async ( readonly prefix: string; readonly containerSha256: string; readonly iterator: AsyncIterator; - readonly owned: boolean; }> = [ { reader, prefix, containerSha256, iterator: reader.entries(context.signal)[Symbol.asyncIterator](), - owned: false, }, ]; + const ownedReaders: ArtifactReader[] = []; + let failure: { readonly cause: unknown } | undefined; try { while (stack.length > 0) { const frame = stack.at(-1); @@ -131,7 +131,6 @@ const visitReader = async ( const next = await frame.iterator.next(); if (next.done) { stack.pop(); - if (frame.owned) await frame.reader.close(); continue; } const entry = next.value; @@ -175,13 +174,14 @@ const visitReader = async ( ); context.containers.push(inventory); const nested = new AsarArtifactReader(entry.adapterKey); + ownedReaders.push(nested); stack.push({ reader: nested, prefix: path, containerSha256: inventory.sha256, iterator: nested.entries(context.signal)[Symbol.asyncIterator](), - owned: true, }); + await nested.prepareContainer(inventory.sha256, context.signal); continue; } const expected = context.expected.get(path); @@ -202,16 +202,33 @@ const visitReader = async ( text, }); } + } catch (cause: unknown) { + failure = { cause }; } finally { - await Promise.allSettled( - stack - .filter(({ owned }) => owned) - .map(async ({ reader, iterator }) => { - await iterator.return?.(); - await reader.close(); - }), - ); + for (const { iterator } of stack) { + try { + await iterator.return?.(); + } catch (cause: unknown) { + failure ??= { cause }; + } + } + for (const owned of ownedReaders.reverse()) { + try { + await owned.close(); + } catch (cause: unknown) { + failure = { + cause: ArtifactReaderFailure.withCleanup( + failure?.cause ?? cause, + ArtifactReaderFailure.cleanupObservation( + cause, + `nested ASAR reader for ${prefix}`, + ), + ), + }; + } + } } + if (failure !== undefined) throw failure.cause; }; const readText = async ( diff --git a/tests/boundary/filesystem/asarInventoryFreshness.test.ts b/tests/boundary/filesystem/asarInventoryFreshness.test.ts index 91cdc81b6..da9db6731 100644 --- a/tests/boundary/filesystem/asarInventoryFreshness.test.ts +++ b/tests/boundary/filesystem/asarInventoryFreshness.test.ts @@ -1,10 +1,13 @@ -import { mkdir, rm, symlink, writeFile } from "node:fs/promises"; +import { lstat, mkdir, rm, symlink, writeFile } from "node:fs/promises"; import { join, sep } from "node:path"; +import { Readable } from "node:stream"; import { buffer } from "node:stream/consumers"; import { createPackage, listPackage, uncache } from "@electron/asar"; import { describe, expect, it } from "vitest"; +import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js"; +import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js"; import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js"; import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -165,7 +168,121 @@ describe("ASAR inventory freshness", () => { } }, ); +}); +describe("ASAR captured-byte identity", () => { + it("rejects same-size nested-container replacement between hashing and interpretation", async () => { + const fixture = await archiveFixture(); + const originalSize = (await lstat(fixture.archive)).size; + const directory = new DirectoryArtifactReader(fixture.bundle); + await expect( + scanCanonicalArtifactInventory(fixture.bundle, {}, async () => ({ + format: directory.format, + entries: (signal) => directory.entries(signal), + provenance: () => directory.provenance(), + close: () => directory.close(), + async open(entry, signal) { + const source = await directory.open(entry, signal); + return Readable.from( + (async function* () { + yield* source; + await fixture.replace(); + expect((await lstat(fixture.archive)).size).toBe(originalSize); + })(), + ); + }, + })), + ).rejects.toMatchObject({ + reason: "integrity", + message: expect.stringContaining("changed before interpretation"), + }); + }); + + it("isolates interleaved readers from replacement headers and packed bytes", async () => { + const fixture = await archiveFixture(); + await writeFile(join(fixture.source, "second.js"), "original metadata"); + await createPackage(fixture.source, fixture.archive); + const first = new AsarArtifactReader(fixture.archive); + const second = new AsarArtifactReader(fixture.archive); + const left = first.entries()[Symbol.asyncIterator](); + const right = second.entries()[Symbol.asyncIterator](); + try { + const initial = await left.next(); + if (initial.done) throw new Error("Expected first member"); + expect(initial.value.path).toBe("old.js"); + await fixture.replace(); + await writeFile(join(fixture.source, "second.js"), "replaced metadata"); + await createPackage(fixture.source, fixture.archive); + const replacement = await right.next(); + if (replacement.done) throw new Error("Expected replacement member"); + expect(replacement.value.path).toBe("new.js"); + const originalMember = await left.next(); + const replacementMember = await right.next(); + if (originalMember.done || replacementMember.done) + throw new Error("Expected second members"); + expect(originalMember.value.declaredSha256).not.toBe( + replacementMember.value.declaredSha256, + ); + expect( + (await buffer(await first.open(originalMember.value))).toString(), + ).toBe("original metadata"); + await first.close(); + expect( + (await buffer(await second.open(replacementMember.value))).toString(), + ).toBe("replaced metadata"); + } finally { + await left.return?.(); + await right.return?.(); + await first.close(); + await second.close(); + } + }); + + it("retains a completed inventory and snapshot ownership when cleanup fails", async () => { + const fixture = await archiveFixture(); + const attempts: string[] = []; + const reader = new AsarArtifactReader( + fixture.archive, + undefined, + async (path) => { + attempts.push(path); + if (attempts.length === 1) throw new Error("snapshot removal denied"); + await rm(path, { recursive: true, force: true }); + }, + ); + try { + const failure: unknown = await scanCanonicalArtifactInventory( + fixture.archive, + {}, + async () => reader, + ).catch((cause: unknown) => cause); + expect(failure).toMatchObject({ + cleanup: { resources: [attempts[0]] }, + partialObservation: { + kind: "artifact-inventory", + inventory: { + occurrences: expect.arrayContaining([ + expect.objectContaining({ + logical_path: "old.js", + hash_status: "verified", + }), + ]), + }, + }, + }); + const root = attempts[0]; + if (root === undefined) throw new Error("Expected owned snapshot"); + expect((await lstat(root)).isDirectory()).toBe(true); + await reader.close(); + expect(attempts).toEqual([root, root]); + await expect(lstat(root)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await reader.close(); + } + }); +}); + +describe("ASAR reader lifecycle", () => { it("refreshes a header cached before the reader was created", async () => { const fixture = await archiveFixture(); try { diff --git a/tests/boundary/filesystem/asarStreamingAllocation.test.ts b/tests/boundary/filesystem/asarStreamingAllocation.test.ts index 630091584..cc9438179 100644 --- a/tests/boundary/filesystem/asarStreamingAllocation.test.ts +++ b/tests/boundary/filesystem/asarStreamingAllocation.test.ts @@ -69,11 +69,6 @@ describe("ASAR entry streaming", () => { await writeFile(join(source, "small.js"), "module.exports = 1;\n"); await createPackageWithOptions(source, archive, {}); - const identity = await lstat(archive); - const probe = await openFile(archive, "r"); - expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0); - await probe.close(); - await waitForNoMatchingDescriptor(identity); const reader = new AsarArtifactReader(archive); try { @@ -83,6 +78,12 @@ describe("ASAR entry streaming", () => { } const entry = entries.find(({ path }) => path === "small.js"); if (entry === undefined) throw new Error("Expected packed ASAR member"); + const snapshot = await reader.openContainer(); + const identity = await lstat(snapshot.path); + await buffer(snapshot); + const probe = await openFile(snapshot.path, "r"); + expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0); + await probe.close(); expect(await matchingDescriptorCount(identity)).toBe(0); const output = await reader.open(entry); expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0); @@ -108,7 +109,6 @@ describe("ASAR entry streaming", () => { await writeFile(join(source, "small.js"), "module.exports = 1;\n"); await createPackageWithOptions(source, archive, {}); - const identity = await lstat(archive); const reader = new AsarArtifactReader(archive); try { @@ -116,6 +116,9 @@ describe("ASAR entry streaming", () => { for await (const entry of reader.entries()) entries.push(entry); const entry = entries.find(({ path }) => path === "small.js"); if (entry === undefined) throw new Error("Expected packed ASAR member"); + const snapshot = await reader.openContainer(); + const identity = await lstat(snapshot.path); + await buffer(snapshot); const controller = new AbortController(); const opening = reader.open(entry, controller.signal); controller.abort(); @@ -127,7 +130,7 @@ describe("ASAR entry streaming", () => { }, ); - it("classifies a missing packed member container as an I/O failure", async () => { + it("keeps captured packed bytes readable after the original container disappears", async () => { const root = await createTestTempDirectory("rea-asar-missing-member-"); const source = join(root, "source"); const archive = join(root, "fixture.asar"); @@ -142,10 +145,9 @@ describe("ASAR entry streaming", () => { const entry = entries.find(({ path }) => path === "small.js"); if (entry === undefined) throw new Error("Expected packed ASAR member"); await rm(archive); - await expect(reader.open(entry)).rejects.toMatchObject({ - reason: "io", - cause: { code: "ENOENT" }, - }); + expect((await buffer(await reader.open(entry))).toString()).toBe( + "module.exports = 1;\n", + ); } finally { await reader.close(); } @@ -205,7 +207,7 @@ describe("ASAR entry producer identity", () => { ["packed to unpacked", false], ["unpacked to packed", true], ] as const)( - "rejects a retained %s entry after a new entries pass", + "rejects a retained %s entry after closing and recapturing the archive", async (_transition, wasUnpacked) => { const root = await createTestTempDirectory("rea-asar-entry-refresh-"); const source = join(root, "source"); @@ -236,6 +238,7 @@ describe("ASAR entry producer identity", () => { archive, wasUnpacked ? {} : { unpack: "small.js" }, ); + await reader.close(); const currentEntries = []; for await (const entry of reader.entries()) currentEntries.push(entry); const current = currentEntries.find(({ path }) => path === "small.js"); @@ -345,7 +348,7 @@ describe("ASAR read failures", () => { ); it.each(["missing", "replaced"] as const)( - "validates the container before returning a zero-length member when it is %s", + "reads a captured zero-length member when the original container is %s", async (change) => { const root = await createTestTempDirectory("rea-asar-empty-member-"); const source = join(root, "source"); @@ -363,11 +366,7 @@ describe("ASAR read failures", () => { if (change === "missing") await rm(archive); else await writeFile(archive, "replacement container"); - await expect(reader.open(entry)).rejects.toMatchObject( - change === "missing" - ? { reason: "io", cause: { code: "ENOENT" } } - : { reason: "integrity" }, - ); + expect(await buffer(await reader.open(entry))).toHaveLength(0); } finally { await reader.close(); } diff --git a/tests/boundary/filesystem/javascriptArtifactContentIdentity.test.ts b/tests/boundary/filesystem/javascriptArtifactContentIdentity.test.ts index 1871e59c5..2acfb8911 100644 --- a/tests/boundary/filesystem/javascriptArtifactContentIdentity.test.ts +++ b/tests/boundary/filesystem/javascriptArtifactContentIdentity.test.ts @@ -122,7 +122,7 @@ describe("JavaScript artifact ingestion content identities", () => { } }); - it("retains native filesystem errors for outer IO classification", async () => { + it("retains filesystem error context in typed IO failures", async () => { const { archive } = await fixture(); const snapshot = await scanArtifactInventory(archive); await rm(archive); @@ -130,7 +130,7 @@ describe("JavaScript artifact ingestion content identities", () => { try { await expect( readJavaScriptArtifactFiles(reader, snapshot), - ).rejects.toMatchObject({ code: "ENOENT" }); + ).rejects.toMatchObject({ reason: "io", cause: { code: "ENOENT" } }); } finally { await reader.close(); } From 4951a897c53bb6882300c5d7a9660a3f43e374f5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:19:58 +0800 Subject: [PATCH 110/189] fix(browser)!: preserve payload shapes and WebMCP declarations Retain primitive and nested array types with typed paths, and compare only mutually observed body shapes while preserving selected coverage uncertainty. Return full untrusted WebMCP input declarations with canonical digests, without resolving references or invoking tools. BREAKING CHANGE: JSON shape paths now contain typed property and array-element segments. WebMCP input_schema_shape is replaced by input_schema and input_schema_sha256, retaining declared examples and defaults. --- docs/browser-observation.md | 4 +- scripts/lib/browser-verifier-assertions.mjs | 15 ++- src/browser/CdpWebMcpDiscovery.ts | 21 ++-- src/domain/jsonShape.test.ts | 104 +++++++++++++--- src/domain/jsonShape.ts | 75 ++++++++---- src/domain/webCaptureDiff.ts | 94 +++++++++++++-- src/domain/webMcpDiscovery.ts | 7 +- ...cdpBrowserProvider.document_script.test.ts | 112 ++++++++++++++++-- .../cdpBrowserProvider.sensitive_data.test.ts | 29 ++++- .../browser/cdpJsonShapeComparison.test.ts | 83 +++++++++++++ tests/fixtures/fakeCdpBrowserEvents.ts | 2 +- tests/fixtures/fakeCdpBrowserTypes.ts | 2 + 12 files changed, 463 insertions(+), 85 deletions(-) diff --git a/docs/browser-observation.md b/docs/browser-observation.md index dae77e066..0cebe1649 100644 --- a/docs/browser-observation.md +++ b/docs/browser-observation.md @@ -14,7 +14,7 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools - `inspect_web_page` / `rea inspect-web-page` captures DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally selected storage key names, redacted storage-content fingerprints, or script sources. - `analyze_web_bundle` / `rea analyze-web-bundle` parses selected script artifacts without execution and derives chunk edges, route and endpoint candidates, vendor fingerprints, static WebMCP declarations, and optionally source-map/original-source evidence. - `observe_web_session` / `rea observe-web-session` arms an observation window of the requested duration for an external user action and records ordered reload, SPA navigation, redirect, failure, lifecycle, and target-termination metadata. -- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to return every in-scope registration and its complete structural input-schema summary inline. Registrations with the same name and URL in distinct observed frames retain separate identities. `tool_key` includes the observed frame ID; it is not a stable identity across navigation or browser sessions. Same-frame registration updates replace that owner only, and removal leaves other owners intact. REA never exposes `WebMCP.invokeTool`; malformed protocol payloads fail explicitly instead of returning incomplete tool metadata. +- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to return every in-scope registration and its complete observed `input_schema` declaration and canonical `input_schema_sha256` digest inline. Declarations are untrusted JSON data, including declared types, required fields, enums, examples and reference URLs. REA does not resolve schema references. These fields replace `input_schema_shape`. Registrations with the same name and URL in distinct observed frames retain separate identities. `tool_key` includes the observed frame ID; it is not a stable identity across navigation or browser sessions. Same-frame registration updates replace that owner only, and removal leaves other owners intact. REA never exposes `WebMCP.invokeTool`; malformed protocol payloads fail explicitly instead of returning incomplete tool metadata. - `compare_web_captures` / `rea compare-web-captures` compares passive captures or exact-step-aligned browser scenarios. Scenario results commit reproducible literal normalization and expose alignment failures plus artifact-level action, screenshot, DOM, accessibility, URL, history, storage, and event differences. Missing or truncated evidence is never treated as equivalence. - `capture_web_screenshot` / `rea capture-web-screenshot` returns a content-addressed visible-viewport PNG. - `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services. @@ -134,7 +134,7 @@ REA retains local observation data and removes only URL userinfo credentials, ex - DOM snapshots retain node types, node names, value lengths, and attribute names, but not text or attribute values. - Accessibility structure and roles are retained by default, while names and descriptions require `include_accessibility_text: true`. - Network observations retain method, status, MIME type, size, type, initiator stack location, and complete URLs with userinfo credentials removed. Redirects reported by CDP are attached as ordered `redirects` on the one request ID, with the prior request URL, CDP response URL, method/type, response status/MIME/encoded length, request timestamp, and the next `requestWillBeSent` event timestamp. CDP delivers `redirectResponse` with that next request event, so the latter is an event boundary rather than an exact response timestamp. Redirect response headers and bodies are discarded; hops outside the selected origins are discarded with the request chain. Headers are discarded after an allowlisted projection of length/encoding, structured CSP/Link/policy fields, and untrusted agent hints. Cookies and authorization headers are never retained. -- Request/response bodies are not requested or parsed by default. When selected, only allowed-origin JSON media types are read, converted immediately to complete value-free property paths/types, and discarded. `Network.getResponseBody` is never sent unless JSON body shape capture is selected. +- Request/response bodies are not requested or parsed by default. When selected, only allowed-origin JSON media types are read, converted immediately to complete value-free typed paths, types and observation counts, and discarded. Each path segment is either `{ "kind": "property", "name": "raw property name" }` or `{ "kind": "array-element" }`; array-element types include primitives and nested arrays. Literal `*` properties remain distinct from array elements. `Network.getResponseBody` is never sent unless JSON body shape capture is selected. Comparison uses body shapes only when both captures selected them, and compares request/response shapes only where both observations provide those facts. Unavailable or truncated selected coverage makes equivalence unknown; observed differences still report changed. - Console observations with a stack source retain call type, argument types, timestamp, and source location. When console text capture is selected, already-delivered primitive values are retained verbatim; objects, getters, and remote properties are never expanded. - WebSocket observations retain direction, opcode, and payload byte length. When shape capture is selected, text frames are classified as text or complete value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained. - Storage observations always redact values. Key names, IndexedDB names, and cache names require `include_storage_keys`; stable content fingerprints require the additional `include_storage_fingerprints` selection. Cookie fingerprints cover cookies applicable to the current main-frame URL, including its path, rather than every cookie path on that origin. Other storage remains scoped to the origin. Cache bodies above 64 KiB and partial IndexedDB remote objects make fingerprint coverage incomplete, so identical observations remain `unknown`. diff --git a/scripts/lib/browser-verifier-assertions.mjs b/scripts/lib/browser-verifier-assertions.mjs index b0c9b88d5..8e484afa1 100644 --- a/scripts/lib/browser-verifier-assertions.mjs +++ b/scripts/lib/browser-verifier-assertions.mjs @@ -209,10 +209,16 @@ export function assertSensitiveShapes(result) { (item) => item.url.includes("/api") && item.body_shapes.request?.properties.some( - ({ path }) => path === "/token", + ({ path }) => + path.length === 1 && + path[0].kind === "property" && + path[0].name === "token", ) && item.body_shapes.response?.properties.some( - ({ path }) => path === "/secret", + ({ path }) => + path.length === 1 && + path[0].kind === "property" && + path[0].name === "secret", ), ); if (request === undefined) @@ -244,7 +250,10 @@ export function assertSensitiveShapes(result) { (event) => event.payload_shape?.format === "json" && event.payload_shape.json_shape?.properties.some( - ({ path }) => path === "/token", + ({ path }) => + path.length === 1 && + path[0].kind === "property" && + path[0].name === "token", ), ) ) diff --git a/src/browser/CdpWebMcpDiscovery.ts b/src/browser/CdpWebMcpDiscovery.ts index 240043f08..1cdbd3334 100644 --- a/src/browser/CdpWebMcpDiscovery.ts +++ b/src/browser/CdpWebMcpDiscovery.ts @@ -5,7 +5,8 @@ import type { DiscoverWebMcpToolsInput, WebMcpDiscovery, } from "../domain/webMcpDiscovery.js"; -import { inferJsonShape } from "../domain/jsonShape.js"; +import { jsonValueSchema } from "../domain/jsonValue.js"; +import { digestCanonicalValue } from "../domain/canonicalDigest.js"; import { compositeKey } from "../domain/unicodeCodePointOrder.js"; import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js"; import type { CdpConnection, CdpEvent } from "./CdpConnection.js"; @@ -413,6 +414,10 @@ const normalizeTool = ( } const description = cdpStringValue(value.description) ?? ""; const annotations = recordValue(value.annotations); + const declaration = jsonValueSchema.safeParse(value.inputSchema); + if (!declaration.success) + completeness.exclude("webmcp_tools", "invalid_protocol_value"); + const schema = declaration.success ? declaration.data : null; return { tool_key: toolKey(frame.url, frameId, name), name, @@ -424,7 +429,10 @@ const normalizeTool = ( numberValue(value.backendNodeId) === undefined ? "imperative" : "declarative", - input_schema_shape: schemaShape(value.inputSchema), + input_schema: schema, + input_schema_sha256: declaration.success + ? digestCanonicalValue(schema) + : null, annotations: { read_only: booleanOrNull(annotations?.readOnly), untrusted_content: booleanOrNull(annotations?.untrustedContent), @@ -438,15 +446,6 @@ const normalizeTool = ( }; }; -const schemaShape = (value: unknown) => { - if (recordValue(value) === undefined) return null; - const encoded = JSON.stringify(value); - const shape = inferJsonShape(encoded); - if (shape === null) - throw new BrowserObservationError("inspect_web_page", "protocol_error"); - return shape; -}; - const registrationSource = ( stack: UnknownRecord | undefined, allowedOrigins: ReadonlySet, diff --git a/src/domain/jsonShape.test.ts b/src/domain/jsonShape.test.ts index e1a5dad2b..136c58381 100644 --- a/src/domain/jsonShape.test.ts +++ b/src/domain/jsonShape.test.ts @@ -2,6 +2,9 @@ import { describe, expect, it } from "vitest"; import { inferJsonShape } from "./jsonShape.js"; +const property = (name: string) => ({ kind: "property" as const, name }); +const element = { kind: "array-element" as const }; + describe("inferJsonShape", () => { it("retains paths and types without retaining JSON values", () => { const shape = inferJsonShape( @@ -18,14 +21,18 @@ describe("inferJsonShape", () => { expect(shape).toMatchObject({ root_type: "object", properties: expect.arrayContaining([ - { path: "/token", types: ["string"], observations: 1 }, { - path: "/users/*/id", + path: [property("token")], + types: ["string"], + observations: 1, + }, + { + path: [property("users"), element, property("id")], types: ["number", "string"], observations: 2, }, { - path: "/users/*/active", + path: [property("users"), element, property("active")], types: ["boolean"], observations: 2, }, @@ -35,11 +42,36 @@ describe("inferJsonShape", () => { expect(JSON.stringify(shape)).not.toContain("second-secret"); }); + it("distinguishes array elements from literal star properties and counts primitive types", () => { + const shape = inferJsonShape('{"items":[{"*":1},[true,"x",null],2]}'); + expect(shape?.properties).toEqual( + expect.arrayContaining([ + { + path: [property("items"), element], + types: ["array", "number", "object"], + observations: 3, + }, + { + path: [property("items"), element, property("*")], + types: ["number"], + observations: 1, + }, + { + path: [property("items"), element, element], + types: ["boolean", "null", "string"], + observations: 3, + }, + ]), + ); + }); + it("rejects malformed JSON", () => { expect(inferJsonShape("not-json")).toBeNull(); }); +}); - it("preserves pointer escaping and code-point ordering independently of key insertion order", () => { +describe("JSON shape completeness and ordering", () => { + it("preserves raw property names and code-point ordering independently of key insertion order", () => { for (const reverse of [false, true]) { const object = (number: number, value: unknown) => { const entries = [ @@ -64,24 +96,66 @@ describe("inferJsonShape", () => { node_count: 23, max_depth_observed: 4, properties: [ - { path: "/nested", types: ["array"], observations: 1 }, - { path: "/nested/*/A", types: ["boolean"], observations: 2 }, - { path: "/nested/*/_", types: ["boolean"], observations: 2 }, - { path: "/nested/*/a", types: ["boolean"], observations: 2 }, { - path: "/nested/*/e\u0301~1~0", + path: [property("nested")], + types: ["array"], + observations: 1, + }, + { + path: [property("nested"), element], + types: ["object"], + observations: 2, + }, + { + path: [property("nested"), element, property("A")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("_")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("a")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("e\u0301/~")], types: ["array", "null"], observations: 2, }, { - path: "/nested/*/e\u0341~1~0", + path: [property("nested"), element, property("e\u0301/~"), element], + types: ["null"], + observations: 1, + }, + { + path: [property("nested"), element, property("e\u0341/~")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("z")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("é/~")], + types: ["number"], + observations: 2, + }, + { + path: [property("nested"), element, property("\uE000")], + types: ["boolean"], + observations: 2, + }, + { + path: [property("nested"), element, property("\u{10000}")], types: ["boolean"], observations: 2, }, - { path: "/nested/*/z", types: ["boolean"], observations: 2 }, - { path: "/nested/*/é~1~0", types: ["number"], observations: 2 }, - { path: "/nested/*/\uE000", types: ["boolean"], observations: 2 }, - { path: "/nested/*/\u{10000}", types: ["boolean"], observations: 2 }, ], }); } @@ -96,7 +170,7 @@ describe("inferJsonShape", () => { expect(shape?.properties).toHaveLength(5_001); expect(shape?.node_count).toBe(5_002); expect(shape?.properties).toContainEqual({ - path: "/field_5000", + path: [property("field_5000")], types: ["number"], observations: 1, }); diff --git a/src/domain/jsonShape.ts b/src/domain/jsonShape.ts index f8d844aaf..2976d3ceb 100644 --- a/src/domain/jsonShape.ts +++ b/src/domain/jsonShape.ts @@ -12,6 +12,12 @@ const jsonValueTypeSchema = z.enum([ ]); type JsonValueType = z.infer; +const jsonShapePathSegmentSchema = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("property"), name: z.string() }), + z.object({ kind: z.literal("array-element") }), +]); +type JsonShapePathSegment = z.infer; + /** Value-free structural summary of one approved JSON payload. */ export const jsonShapeSchema = z.object({ root_type: jsonValueTypeSchema, @@ -19,7 +25,7 @@ export const jsonShapeSchema = z.object({ max_depth_observed: z.number().int().min(0), properties: z.array( z.object({ - path: z.string(), + path: z.array(jsonShapePathSegmentSchema).min(1), types: z.array(jsonValueTypeSchema).min(1), observations: z.number().int().min(1), }), @@ -39,13 +45,17 @@ export const inferJsonShape = (text: string): JsonShape | null => { } const properties = new Map< string, - { readonly types: Set; observations: number } + { + readonly path: JsonShapePathSegment[]; + readonly types: Set; + observations: number; + } >(); const pending: Array<{ readonly value: unknown; - readonly path: string; + readonly path: JsonShapePathSegment[]; readonly depth: number; - }> = [{ value: root, path: "", depth: 0 }]; + }> = [{ value: root, path: [], depth: 0 }]; let nodeCount = 0; let maxDepthObserved = 0; while (pending.length > 0) { @@ -53,11 +63,26 @@ export const inferJsonShape = (text: string): JsonShape | null => { if (current === undefined) break; nodeCount += 1; maxDepthObserved = Math.max(maxDepthObserved, current.depth); + if (current.path.length > 0) { + const key = JSON.stringify(current.path); + const type = jsonValueType(current.value); + const existing = properties.get(key); + if (existing === undefined) + properties.set(key, { + path: current.path, + types: new Set([type]), + observations: 1, + }); + else { + existing.types.add(type); + existing.observations += 1; + } + } if (Array.isArray(current.value)) { for (let index = current.value.length - 1; index >= 0; index -= 1) pending.push({ value: current.value[index], - path: `${current.path}/*`, + path: [...current.path, { kind: "array-element" }], depth: current.depth + 1, }); continue; @@ -68,15 +93,10 @@ export const inferJsonShape = (text: string): JsonShape | null => { const entry = allEntries[index]; if (entry === undefined) continue; const [name, value] = entry; - const path = `${current.path}/${pointerName(name)}`; - const type = jsonValueType(value); - const existing = properties.get(path); - if (existing === undefined) - properties.set(path, { types: new Set([type]), observations: 1 }); - else { - existing.types.add(type); - existing.observations += 1; - } + const path: JsonShapePathSegment[] = [ + ...current.path, + { kind: "property", name }, + ]; pending.push({ value, path, depth: current.depth + 1 }); } } @@ -84,13 +104,13 @@ export const inferJsonShape = (text: string): JsonShape | null => { root_type: jsonValueType(root), node_count: nodeCount, max_depth_observed: maxDepthObserved, - properties: [...properties.entries()] - .map(([path, value]) => ({ - path, + properties: [...properties.values()] + .map((value) => ({ + path: value.path, types: [...value.types].sort(), observations: value.observations, })) - .sort((left, right) => compareUnicodeCodePoints(left.path, right.path)), + .sort((left, right) => compareShapePaths(left.path, right.path)), }); }; @@ -112,5 +132,20 @@ const jsonValueType = (value: unknown): JsonValueType => { const isRecord = (value: unknown): value is Readonly> => typeof value === "object" && value !== null && !Array.isArray(value); -const pointerName = (value: string): string => - value.replaceAll("~", "~0").replaceAll("/", "~1"); +const compareShapePaths = ( + left: readonly JsonShapePathSegment[], + right: readonly JsonShapePathSegment[], +): number => { + for (let index = 0; index < Math.min(left.length, right.length); index += 1) { + const a = left[index]; + const b = right[index]; + if (a === undefined || b === undefined) break; + const order = + compareUnicodeCodePoints(a.kind, b.kind) || + (a.kind === "property" && b.kind === "property" + ? compareUnicodeCodePoints(a.name, b.name) + : 0); + if (order !== 0) return order; + } + return left.length - right.length; +}; diff --git a/src/domain/webCaptureDiff.ts b/src/domain/webCaptureDiff.ts index cee5096d3..08c896818 100644 --- a/src/domain/webCaptureDiff.ts +++ b/src/domain/webCaptureDiff.ts @@ -196,13 +196,7 @@ const compareWebCaptureDimensions = ( sectionsComplete(after, ["resources"]), "Resource inventory was incomplete in at least one observation.", ), - network: compareDimension( - networkMap(before), - networkMap(after), - sectionsComplete(before, ["network_requests"]) && - sectionsComplete(after, ["network_requests"]), - "Network capture is attach-window limited or incomplete.", - ), + network: networkDimension(before, after), metadata: compareDimension( singleton("metadata", digestCanonicalValue(metadataProjection(before))), singleton("metadata", digestCanonicalValue(metadataProjection(after))), @@ -229,16 +223,85 @@ const keyed = ( values.map((value) => [identity(value), digestCanonicalValue(value)]), ); +type BodyShapeSources = { + readonly request: boolean; + readonly response: boolean; +}; + +const bodyShapesSelected = (inspection: WebPageInspection): boolean => + !inspection.completeness.excluded.some( + ({ section, reason }) => + section === "json_body_shapes" && reason === "not_approved", + ) && + (inspection.network.requests.length === 0 || + inspection.network.requests.some( + ({ body_shapes }) => body_shapes.status !== "not_approved", + )); + +const networkIdentity = ( + request: WebPageInspection["network"]["requests"][number], +): string => + `net_${digestCanonicalValue({ method: request.method, url: request.url, resource_type: request.resource_type })}`; + +const networkDimension = ( + before: WebPageInspection, + after: WebPageInspection, +): Dimension => { + const selected = bodyShapesSelected(before) && bodyShapesSelected(after); + const sources = new Map(); + if (selected) { + const observedSources = (inspection: WebPageInspection) => { + const result = new Map(); + for (const request of inspection.network.requests) { + const identity = networkIdentity(request); + const previous = result.get(identity); + result.set(identity, { + request: + previous?.request !== false && request.body_shapes.request !== null, + response: + previous?.response !== false && + request.body_shapes.response !== null, + }); + } + return result; + }; + const left = observedSources(before); + const right = observedSources(after); + for (const [identity, coverage] of left) { + const next = right.get(identity); + sources.set(identity, { + request: coverage.request && next?.request === true, + response: coverage.response && next?.response === true, + }); + } + } + const shapesComplete = + !selected || + [before, after].every( + (inspection) => + sectionsComplete(inspection, ["json_body_shapes"]) && + inspection.network.requests.every( + ({ body_shapes }) => body_shapes.status === "included", + ), + ); + return compareDimension( + networkMap(before, sources), + networkMap(after, sources), + sectionsComplete(before, ["network_requests"]) && + sectionsComplete(after, ["network_requests"]) && + shapesComplete, + "Network capture or selected JSON body-shape coverage is attach-window limited, unavailable, or incomplete.", + ); +}; + const networkMap = ( inspection: WebPageInspection, + sources: ReadonlyMap, ): ReadonlyMap => { const grouped = new Map(); for (const request of inspection.network.requests) { - const identity = `net_${digestCanonicalValue({ - method: request.method, - url: request.url, - resource_type: request.resource_type, - })}`; + const identity = networkIdentity(request); + const shapes = sources.get(identity); const values = grouped.get(identity) ?? []; values.push({ status: request.status, @@ -252,7 +315,12 @@ const networkMap = ( }) => redirect, ), initiator: request.initiator, - body_shapes: request.body_shapes, + ...(shapes?.request === true + ? { request_shape: request.body_shapes.request } + : {}), + ...(shapes?.response === true + ? { response_shape: request.body_shapes.response } + : {}), }); grouped.set(identity, values); } diff --git a/src/domain/webMcpDiscovery.ts b/src/domain/webMcpDiscovery.ts index fa429e453..f1a3f3b12 100644 --- a/src/domain/webMcpDiscovery.ts +++ b/src/domain/webMcpDiscovery.ts @@ -6,8 +6,8 @@ import { browserEndpointSchema, } from "./browserObservation.js"; import { browserVersionSchema } from "./browserObservationSchemas.js"; -import { jsonShapeSchema } from "./jsonShape.js"; -import { prefixedDigestSchema } from "./../domain/digests.js"; +import { jsonValueSchema } from "./jsonValue.js"; +import { digestSchema, prefixedDigestSchema } from "./../domain/digests.js"; /** Input for passive discovery of page-registered WebMCP tools. */ export const discoverWebMcpToolsInputSchema = z.strictObject({ @@ -28,7 +28,8 @@ const webMcpToolSchema = z.object({ frame_url: z.string(), owner_origin: z.string(), declaration_kind: z.enum(["declarative", "imperative"]), - input_schema_shape: jsonShapeSchema.nullable(), + input_schema: jsonValueSchema.nullable(), + input_schema_sha256: digestSchema.nullable(), annotations: z.object({ read_only: z.boolean().nullable(), untrusted_content: z.boolean().nullable(), diff --git a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts index 7131b30d8..b74c60081 100644 --- a/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.document_script.test.ts @@ -1,3 +1,8 @@ +import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js"; +import type { JsonValue } from "../../../src/domain/jsonValue.js"; +import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js"; +import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js"; + import { describe, expect, it } from "vitest"; import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js"; @@ -292,8 +297,8 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => { const serialized = JSON.stringify(result.value); expect(serialized).toContain("tool-secret"); expect(serialized).toContain("tool-source-secret"); - for (const secret of ["schema-secret", "private-tool-secret"]) - expect(serialized).not.toContain(secret); + expect(serialized).toContain("schema-secret"); + expect(serialized).not.toContain("private-tool-secret"); const methods = browser.commands.map(({ method }) => method); expect(methods).toContain("WebMCP.enable"); expect(methods).not.toContain("WebMCP.invokeTool"); @@ -406,6 +411,85 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => { }); describe("CdpBrowserProvider WebMCP inventory completeness", () => { + it("compares full untrusted declarations independently of object-key order", async () => { + const declaration: JsonValue = { + type: "object", + properties: { value: { type: "string", enum: ["one", "two"] } }, + required: ["value"], + $ref: "https://untrusted.invalid/schema.json", + examples: [{ token: "caller-schema-value" }], + }; + const options: { webMcpTools: boolean; webMcpInputSchema: JsonValue } = { + webMcpTools: true, + webMcpInputSchema: declaration, + }; + const browser = await startFakeCdpBrowser(options); + trackBrowser(browser); + const provider = new CdpBrowserProvider(); + const input = { + cdp_endpoint: browser.endpoint, + allowed_origins: [browser.allowedOrigin], + target_id: "allowed-page", + observation_ms: 0, + }; + const inspection = await provider.inspectPage( + inspectWebPageInputSchema.parse(input), + ); + if (!inspection.ok) throw inspection.error; + const discover = async () => { + const result = await provider.discoverWebMcpTools( + discoverWebMcpToolsInputSchema.parse(input), + ); + if (!result.ok) throw result.error; + return result.value; + }; + const before = await discover(); + expect(before.tools.items[0]).toMatchObject({ + input_schema: declaration, + input_schema_sha256: digestCanonicalValue(declaration), + trust: "page-declared-untrusted", + }); + const compare = async (schema: JsonValue) => { + options.webMcpInputSchema = schema; + const after = await discover(); + const diff = compareWebCaptures( + compareWebCapturesInputSchema.parse({ + before: { inspection: inspection.value, webmcp: before }, + after: { inspection: inspection.value, webmcp: after }, + }), + ); + return { after, dimension: diff.dimensions.webmcp }; + }; + const reordered = Object.fromEntries(Object.entries(declaration).reverse()); + const equivalent = await compare(reordered); + expect(equivalent.dimension).toMatchObject({ + status: "unknown", + total_changes: 0, + }); + expect(equivalent.after.tools.items[0]?.input_schema_sha256).toBe( + before.tools.items[0]?.input_schema_sha256, + ); + for (const changed of [ + { + ...declaration, + properties: { value: { type: "number", enum: ["one", "two"] } }, + }, + { ...declaration, required: [] }, + { + ...declaration, + properties: { value: { type: "string", enum: ["two", "three"] } }, + }, + false, + ]) { + const result = await compare(changed); + expect(result.dimension).toMatchObject({ + status: "changed", + total_changes: 1, + changes: [expect.objectContaining({ change: "modified" })], + }); + } + }); + it("retains every field in a large declared WebMCP input schema", async () => { const propertyCount = 5_001; const browser = await startFakeCdpBrowser({ @@ -423,17 +507,21 @@ describe("CdpBrowserProvider WebMCP inventory completeness", () => { ); if (!result.ok) throw result.error; - const shape = result.value.tools.items[0]?.input_schema_shape; - expect( - shape?.properties.filter(({ path }) => - path.startsWith("/properties/field_"), - ), - ).toHaveLength(propertyCount * 2); - expect(shape?.properties).toContainEqual({ - path: "/properties/field_5000/type", - types: ["string"], - observations: 1, + const tool = result.value.tools.items[0]; + expect(tool?.input_schema).toMatchObject({ + type: "object", + properties: { field_5000: { type: "string" } }, }); + if ( + tool?.input_schema === null || + typeof tool?.input_schema !== "object" || + Array.isArray(tool.input_schema) + ) + throw new Error("Expected an observed schema object"); + expect(Object.keys(tool.input_schema.properties ?? {})).toHaveLength( + propertyCount, + ); + expect(tool.input_schema_sha256).toMatch(/^[a-f0-9]{64}$/u); }); }); diff --git a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts index 0c51f200c..e079bead0 100644 --- a/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts +++ b/tests/boundary/browser/cdpBrowserProvider.sensitive_data.test.ts @@ -254,9 +254,15 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", () request: { root_type: "object", properties: expect.arrayContaining([ - expect.objectContaining({ path: "/token", types: ["string"] }), expect.objectContaining({ - path: "/filters/active", + path: [{ kind: "property", name: "token" }], + types: ["string"], + }), + expect.objectContaining({ + path: [ + { kind: "property", name: "filters" }, + { kind: "property", name: "active" }, + ], types: ["boolean"], }), ]), @@ -265,10 +271,20 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", () root_type: "object", properties: expect.arrayContaining([ expect.objectContaining({ - path: "/result/token", + path: [ + { kind: "property", name: "result" }, + { kind: "property", name: "token" }, + ], types: ["string"], }), - expect.objectContaining({ path: "/items/*/id", types: ["number"] }), + expect.objectContaining({ + path: [ + { kind: "property", name: "items" }, + { kind: "array-element" }, + { kind: "property", name: "id" }, + ], + types: ["number"], + }), ]), }, }); @@ -279,7 +295,10 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", () format: "json", json_shape: expect.objectContaining({ properties: expect.arrayContaining([ - expect.objectContaining({ path: "/token", types: ["string"] }), + expect.objectContaining({ + path: [{ kind: "property", name: "token" }], + types: ["string"], + }), ]), }), }), diff --git a/tests/boundary/browser/cdpJsonShapeComparison.test.ts b/tests/boundary/browser/cdpJsonShapeComparison.test.ts index 23890f682..e6dfa8ef7 100644 --- a/tests/boundary/browser/cdpJsonShapeComparison.test.ts +++ b/tests/boundary/browser/cdpJsonShapeComparison.test.ts @@ -63,6 +63,32 @@ describe.each(["request", "response", "base64 response"])( }, ); + it.each([ + { name: "scalar array types", before: "[123]", after: '["a"]' }, + { name: "mixed array types", before: '[1,"a"]', after: "[1,true]" }, + { name: "nested arrays", before: "[[1],null]", after: '[["a"],null]' }, + { + name: "literal star properties", + before: '{"items":[{"*":1},[true]]}', + after: '{"items":[{"*":true},[1]]}', + }, + ])("compares $name without retaining values", async ({ before, after }) => { + const length = Math.max( + Buffer.byteLength(before), + Buffer.byteLength(after), + ); + const captures = comparableCaptures( + source, + before + " ".repeat(length - Buffer.byteLength(before)), + after + " ".repeat(length - Buffer.byteLength(after)), + ); + const result = await compareCaptures(...captures); + expect(result.dimensions.network).toMatchObject({ + status: "changed", + total_changes: 1, + }); + }); + it.each([ { name: "a type change", after: '{"é":null,"e\u0301":null}' }, { name: "a removed key", after: '{"e\u0301":null}' }, @@ -94,6 +120,63 @@ describe.each(["request", "response", "base64 response"])( }, ); +describe("selected JSON body-shape coverage", () => { + it.each(["unavailable", "partial", "truncated"] as const)( + "keeps %s coverage unknown without reporting an availability change", + async (coverage) => { + const before = captureBody("request", "[123]"); + const after = structuredClone(before); + for (const capture of [before, after]) + capture.completeness.attach_limited_sections = []; + const request = after.network.requests[0]; + if (request === undefined) throw new Error("Expected request"); + if (coverage === "truncated") + after.completeness.truncated_sections.push("json_body_shapes"); + else { + request.body_shapes.status = coverage; + request.body_shapes.response = null; + if (coverage === "unavailable") request.body_shapes.request = null; + after.completeness.unavailable_sections.push("json_body_shapes"); + } + expect( + (await compareCaptures(before, after)).dimensions.network, + ).toMatchObject({ status: "unknown", total_changes: 0 }); + expect( + (await compareCaptures(after, after)).dimensions.network.status, + ).toBe("unknown"); + request.status = 503; + expect( + (await compareCaptures(before, after)).dimensions.network.status, + ).toBe("changed"); + }, + ); + + it("ignores shapes when either capture did not request them", async () => { + const before = captureBody("request", "[123]"); + const after = structuredClone(before); + for (const capture of [before, after]) + capture.completeness.attach_limited_sections = []; + after.completeness.excluded.push({ + section: "json_body_shapes", + reason: "not_approved", + count: null, + }); + after.completeness.policy_filtered_sections.push("json_body_shapes"); + for (const request of after.network.requests) + request.body_shapes = { + status: "not_approved", + request: null, + response: null, + }; + expect( + (await compareCaptures(before, after)).dimensions.network, + ).toMatchObject({ status: "unchanged", total_changes: 0 }); + expect( + (await compareCaptures(after, after)).dimensions.network.status, + ).toBe("unchanged"); + }); +}); + const comparableCaptures = ( source: BodySource, beforeBody: string, diff --git a/tests/fixtures/fakeCdpBrowserEvents.ts b/tests/fixtures/fakeCdpBrowserEvents.ts index 5129f74b8..dda7ba3cd 100644 --- a/tests/fixtures/fakeCdpBrowserEvents.ts +++ b/tests/fixtures/fakeCdpBrowserEvents.ts @@ -49,7 +49,7 @@ const emitWebMcpEvents = ( description: "Search orders; authorization=Bearer tool-secret", frameId: "frame-main", backendNodeId: 42, - inputSchema: { + inputSchema: options.webMcpInputSchema ?? { type: "object", properties: inputSchemaProperties, required: ["orderId"], diff --git a/tests/fixtures/fakeCdpBrowserTypes.ts b/tests/fixtures/fakeCdpBrowserTypes.ts index 9abd64992..00d8807c5 100644 --- a/tests/fixtures/fakeCdpBrowserTypes.ts +++ b/tests/fixtures/fakeCdpBrowserTypes.ts @@ -1,3 +1,4 @@ +import type { JsonValue } from "../../src/domain/jsonValue.js"; export interface FakeCdpCommand { readonly id: number; readonly method: string; @@ -100,6 +101,7 @@ export interface FakeOptions { readonly webMcpSameUrlRegistrations?: "retain" | "remove-second"; readonly webMcpFrameCount?: number; readonly webMcpSchemaPropertyCount?: number; + readonly webMcpInputSchema?: JsonValue; readonly webMcpChildLeavesScope?: boolean; readonly webMcpChildTransientBlank?: boolean; readonly webMcpChildRecoversAfterTransient?: boolean; From 4bcea1aa76e3e7ca665197181739c5e27a62c40a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:20:10 +0800 Subject: [PATCH 111/189] fix(javascript): retain array identity after length mutations Keep unknown element coverage on arrays whose length may have changed, preserving intrinsic length presence and subsequent slot mutations through semantic graph and export-return consumers. --- .../JavaScriptSemanticGraphBuilder.test.ts | 67 ++++++++++--------- .../javascriptSemanticMutationValues.ts | 8 ++- .../applicationMutationPresenceMcp.test.ts | 22 ++++++ 3 files changed, 65 insertions(+), 32 deletions(-) diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts index 7794debf9..216aa309c 100644 --- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts @@ -761,37 +761,42 @@ it.each([ }, ); -it("retains array length presence without inventing an exact length", () => { - const graph = graphFor("const root = [, 1]; const length = root.length;"); - const slot = graph.nodes.find( - ({ kind, properties }) => - kind === "property-slot" && properties.property_pointer === "/length", - ); - expect(slot?.properties).toMatchObject({ - name: "length", - presence: "present", - value_status: "unknown", - }); - const trace = queryJavaScriptSemanticGraph(graph, { - seed: { kind: "property", name: "length" }, - direction: "forward-influence", - allowed_relations: ["reads-property"], - }); - expect(trace.seed_node_ids).toEqual([slot?.node_id]); - expect(trace.relations).toContainEqual( - expect.objectContaining({ - source_node_id: slot?.node_id, - relation: "reads-property", - resolution: "resolved", - }), - ); - expect( - graph.relations.some( - ({ target_node_id, relation }) => - target_node_id === slot?.node_id && relation === "defines", - ), - ).toBe(false); -}); +it.each(["", "root.length = 0;", "root.length = query(); root[0] = 9;"])( + "retains array length presence without inventing an exact length after %s", + (mutation) => { + const graph = graphFor( + `const root = [, 1]; ${mutation} const length = root.length;`, + ); + const slot = graph.nodes.find( + ({ kind, properties }) => + kind === "property-slot" && properties.property_pointer === "/length", + ); + expect(slot?.properties).toMatchObject({ + name: "length", + presence: "present", + value_status: "unknown", + }); + const trace = queryJavaScriptSemanticGraph(graph, { + seed: { kind: "property", name: "length" }, + direction: "forward-influence", + allowed_relations: ["reads-property"], + }); + expect(trace.seed_node_ids).toEqual([slot?.node_id]); + expect(trace.relations).toContainEqual( + expect.objectContaining({ + source_node_id: slot?.node_id, + relation: "reads-property", + resolution: "resolved", + }), + ); + expect( + graph.relations.some( + ({ target_node_id, relation }) => + target_node_id === slot?.node_id && relation === "defines", + ), + ).toBe(false); + }, +); it.each([ ["object spread", 'const root = { known: "value", ...dynamic };'], diff --git a/src/domain/javascript/javascriptSemanticMutationValues.ts b/src/domain/javascript/javascriptSemanticMutationValues.ts index 6036bbd2b..70a25a33c 100644 --- a/src/domain/javascript/javascriptSemanticMutationValues.ts +++ b/src/domain/javascript/javascriptSemanticMutationValues.ts @@ -35,7 +35,13 @@ export const invalidateSemanticMutationPath = ( const name = String(key); // Array length writes can remove every index; ordinary named properties // and sparse indices affect only their own slot. - if (name === "length") return unknown; + if (name === "length") + return { + status: "array", + items: [], + unknownItems: true, + omittedItems: null, + }; const observed = value.items.some((item) => item.name === name); const items = value.items.map((item) => item.name === name diff --git a/tests/boundary/mcp/applicationMutationPresenceMcp.test.ts b/tests/boundary/mcp/applicationMutationPresenceMcp.test.ts index 0d4dc57ac..bece1f9bd 100644 --- a/tests/boundary/mcp/applicationMutationPresenceMcp.test.ts +++ b/tests/boundary/mcp/applicationMutationPresenceMcp.test.ts @@ -232,6 +232,24 @@ it.each([ change: "unknown", baseline: 'const result = {kind:"r",count:2};', }, + { + title: "array length mutation", + body: 'const items = [1]; items.length = query(); const result = {kind:"r", length: items.length, items};', + path: "/length", + presence: "present", + valueState: "unknown", + change: "unknown", + baseline: 'const result = {kind:"r",length:1,items:[2]};', + }, + { + title: "array length mutation followed by another write", + body: 'const items = [1]; items.length = 0; items[0] = 9; const result = {kind:"r", length: items.length, items};', + path: "/length", + presence: "present", + valueState: "unknown", + change: "unknown", + baseline: 'const result = {kind:"r",length:1,items:[2]};', + }, { title: "an array hole", body: 'const result = {kind:"r",items:[,]};', @@ -270,6 +288,10 @@ it.each([ expect(projection.static_return_shapes[0]?.fields).toContainEqual( expect.objectContaining({ path, presence, state: valueState }), ); + if (path === "/length") + expect( + projection.static_return_shapes[0]?.property_coverage, + ).toContainEqual({ path: "/items", status: "partial", omitted: null }); const { client, close } = await createApplicationMcpHarness(); onTestFinished(close); const traced = await client.callTool({ From ecc67cab2d85cacda245890ffe84b80ac395d79e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:20:10 +0800 Subject: [PATCH 112/189] ci: enforce architecture guards with portable checkout paths --- package.json | 2 +- scripts/verify/architecture-guards.mjs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index abb5c215e..1c41d19bc 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,7 @@ "precheck:pr": "npm run deps:check", "check:pr": "node scripts/run-exclusive.mjs artifacts turbo run typecheck lint format:check knip metadata:check test:run && npm run docs:check && npm run jscpd && npm run scan:todos", "precheck:ci": "npm run deps:check", - "check:ci": "node scripts/run-exclusive.mjs artifacts turbo run typecheck lint format:check knip metadata:check jscpd scan:todos", + "check:ci": "node scripts/run-exclusive.mjs artifacts turbo run typecheck lint format:check knip metadata:check jscpd scan:todos && npm run verify:architecture-guards", "build:cached": "node scripts/check-dependency-install.mjs && node scripts/run-exclusive.mjs artifacts turbo run artifacts:skills", "format": "oxfmt .", "format:check": "oxfmt --check .", diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index efe2a8df4..ea92bf9d2 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { readFile, readdir } from "node:fs/promises"; -import { join } from "node:path"; +import { join, relative, sep } from "node:path"; +import { fileURLToPath } from "node:url"; // Architecture guards for the strict-identity / best-effort-inference split. // - Evidence ordering must be locale-independent (ICU varies by host), so @@ -15,7 +16,7 @@ import { join } from "node:path"; // Object.values walkers diverge on loc/comment fields and overflow the // stack on deep generated chains. -const root = new URL("../../", import.meta.url).pathname; +const root = fileURLToPath(new URL("../../", import.meta.url)); const listFiles = async (dir) => { const output = []; @@ -42,7 +43,7 @@ const stripComments = (content) => const sources = await listFiles(join(root, "src")); const files = await Promise.all( sources.map(async (path) => ({ - path: path.slice(root.length), + path: relative(root, path).split(sep).join("/"), content: stripComments(await readFile(path, "utf8")), })), ); From 810107a2ad15cc52afd6662aec24d231d8c77225 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:22:20 +0800 Subject: [PATCH 113/189] fix(cli): stream JSON results at the shared command boundary Route ordinary CLI results through the bounded JSON writer after command registration, including managed member inspection. Remove JavaScript-specific output plumbing while preserving filters, envelopes, cancellation, and failure exits. Measure formatted UTF-16 expansion before Incur token counting and return resource_constraint above the runtime string limit, with recovery guidance. Validate output above the real V8 string limit by SHA-256 and exercise the compiled managed provider. Clean-worktree validation: npm run check; 76 focused tests passed, with 2 optional-provider skips; test discovery passed. Fixes #1371. --- src/cli.ts | 15 ++- src/cli/coreAnalysisCommands.ts | 4 +- src/cli/coreBinaryCommands.ts | 12 +- src/cli/electronCommands.ts | 14 +-- src/cli/javascriptApplicationAnalysis.ts | 18 +-- src/cli/jsonOutput.ts | 5 +- src/cli/streamedJsonOutput.ts | 138 ++++++++++++++++++++-- tests/acceptance/managedCliOutput.test.ts | 62 ++++++++++ tests/boundary/cli/jsonOutput.test.ts | 111 ++++++++++++++++- 9 files changed, 314 insertions(+), 65 deletions(-) create mode 100644 tests/acceptance/managedCliOutput.test.ts diff --git a/src/cli.ts b/src/cli.ts index 590887c2a..36dcd1275 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -31,7 +31,10 @@ import { registerJavaScriptRuntimeObservationCommands } from "./cliJavaScriptRun import { registerApplicationCommands } from "./cli/applicationCommands.js"; import { presentOmittableDefaults } from "./cli/omittableDefaults.js"; import type { CliInstance } from "./cli/types.js"; -import type { CliResultOutput } from "./cli/streamedJsonOutput.js"; +import { + streamCliCommandResults, + type CliResultOutput, +} from "./cli/streamedJsonOutput.js"; /** * Build the one-shot Incur CLI without starting Hopper at import time. @@ -64,12 +67,7 @@ export const createCli = ( }); registerSetupCommands(cli, logger, environment); - registerCoreAnalysisCommands( - cli, - logger, - analysis.runDirectAnalysis, - resultOutput, - ); + registerCoreAnalysisCommands(cli, logger, analysis.runDirectAnalysis); registerUtilityCommands(cli, logger, environment, analysis); registerEvmCommands(cli, logger, environment); registerArtifactCommands(cli, logger, analysis.runProviderAnalysis); @@ -89,9 +87,10 @@ export const createCli = ( registerJavaScriptRecoveryCommands(cli, logger, environment); registerAdvancedBrowserCommands(cli, logger); registerBrowserScenarioCommands(cli, logger, environment); - registerElectronCommands(cli, logger, environment, resultOutput); + registerElectronCommands(cli, logger, environment); registerJavaScriptRuntimeObservationCommands(cli, logger); registerApplicationCommands(cli, logger); presentOmittableDefaults(cli); + if (resultOutput !== undefined) streamCliCommandResults(cli, resultOutput); return cli; }; diff --git a/src/cli/coreAnalysisCommands.ts b/src/cli/coreAnalysisCommands.ts index f72ab1076..999c1b23e 100644 --- a/src/cli/coreAnalysisCommands.ts +++ b/src/cli/coreAnalysisCommands.ts @@ -3,15 +3,13 @@ import type { Logger } from "pino"; import { registerCoreBinaryCommands } from "./coreBinaryCommands.js"; import { registerCoreNativeCommands } from "./coreNativeCommands.js"; import type { CliInstance } from "./types.js"; -import type { CliResultOutput } from "./streamedJsonOutput.js"; /** Register core binary and native deep-analysis CLI commands. */ export const registerCoreAnalysisCommands = ( cli: CliInstance, logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], - resultOutput?: CliResultOutput, ): void => { - registerCoreBinaryCommands(cli, logger, runDirectAnalysis, resultOutput); + registerCoreBinaryCommands(cli, logger, runDirectAnalysis); registerCoreNativeCommands(cli, logger, runDirectAnalysis); }; diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index 5130b8634..a916a2c5a 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -15,7 +15,6 @@ import { import type { CliInstance } from "./types.js"; import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js"; import { withCommandCancellation } from "./commandCancellation.js"; -import type { CliResultOutput } from "./streamedJsonOutput.js"; import { javascriptApplicationOptions } from "../cliObservationOptions.js"; /** Register provider-neutral binary overview and procedure CLI commands. */ @@ -23,9 +22,8 @@ export const registerCoreBinaryCommands = ( cli: CliInstance, logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], - resultOutput?: CliResultOutput, ): void => { - registerOverviewCommands(cli, logger, runDirectAnalysis, resultOutput); + registerOverviewCommands(cli, logger, runDirectAnalysis); registerDecompileCommand(cli, logger, runDirectAnalysis); registerFunctionCommand(cli, logger, runDirectAnalysis); registerInstructionsCommand(cli, logger, runDirectAnalysis); @@ -38,7 +36,6 @@ const registerOverviewCommands = ( cli: CliInstance, logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], - resultOutput?: CliResultOutput, ): void => { const overviewOptions = z.object({ snapshot: z @@ -58,11 +55,7 @@ const registerOverviewCommands = ( integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy, }), alias: { integrityPolicy: "integrity-policy" }, - run: async ({ args, options, format }) => { - const output = - resultOutput === undefined - ? undefined - : { output: resultOutput, command: CLI_COMMANDS.analyze, format }; + run: async ({ args, options }) => { // Route JavaScript targets exactly like analyze-javascript-application, // including typed cancellation; cancellation wraps logging so its exit // code is not replaced by the logged failure status. @@ -74,7 +67,6 @@ const registerOverviewCommands = ( input_path: resolve(args.path), integrity_policy: options.integrityPolicy, }, - output, signal, ), ), diff --git a/src/cli/electronCommands.ts b/src/cli/electronCommands.ts index 79dcd7cc1..73e59fec5 100644 --- a/src/cli/electronCommands.ts +++ b/src/cli/electronCommands.ts @@ -24,7 +24,6 @@ import { javascriptApplicationOptions, } from "../cliObservationOptions.js"; import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js"; -import type { CliResultOutput } from "./streamedJsonOutput.js"; import { withCommandCancellation } from "./commandCancellation.js"; /** Register CLI equivalents of the Electron MCP tools. */ @@ -32,11 +31,10 @@ export const registerElectronCommands = ( cli: ReturnType, logger: Logger, environment: Readonly>, - resultOutput?: CliResultOutput, ): void => { registerElectronObservationCommands(cli, logger); registerElectronActiveCommand(cli, logger, environment); - registerJavaScriptApplicationCommand(cli, logger, resultOutput); + registerJavaScriptApplicationCommand(cli, logger); registerJavaScriptRuntimeReconciliationCommand(cli, logger); }; @@ -184,7 +182,6 @@ const registerElectronPageInspection = ( const registerJavaScriptApplicationCommand = ( cli: ReturnType, logger: Logger, - resultOutput?: CliResultOutput, ): void => { cli.command(CLI_COMMANDS.analyzeJavaScriptApplication, { description: @@ -194,7 +191,7 @@ const registerJavaScriptApplicationCommand = ( }), options: javascriptApplicationOptions, alias: { integrityPolicy: "integrity-policy" }, - run: ({ args, options, format }) => + run: ({ args, options }) => withCommandCancellation((signal) => logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () => runCliJavaScriptApplicationAnalysis( @@ -203,13 +200,6 @@ const registerJavaScriptApplicationCommand = ( format: options.artifactFormat, integrity_policy: options.integrityPolicy, }, - resultOutput === undefined - ? undefined - : { - output: resultOutput, - command: CLI_COMMANDS.analyzeJavaScriptApplication, - format, - }, signal, ), ), diff --git a/src/cli/javascriptApplicationAnalysis.ts b/src/cli/javascriptApplicationAnalysis.ts index 150a7a913..26fad1e3e 100644 --- a/src/cli/javascriptApplicationAnalysis.ts +++ b/src/cli/javascriptApplicationAnalysis.ts @@ -2,15 +2,12 @@ import { analyzeJavaScriptApplication } from "../application/javascript/JavaScri import { createProgressReporter } from "../application/ProgressReporter.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import type { CliCommandOutput } from "./streamedJsonOutput.js"; /** Execute the shared one-shot CLI boundary for static JavaScript analysis. */ export const runCliJavaScriptApplicationAnalysis = async ( input: unknown, - output?: CliCommandOutput, signal?: AbortSignal, -): Promise => { - const started = performance.now(); +): Promise => { const progress = createProgressReporter( async (update) => { process.stderr.write(`${JSON.stringify({ rea_progress: update })}\n`); @@ -21,18 +18,7 @@ export const runCliJavaScriptApplicationAnalysis = async ( progress, ...(signal === undefined ? {} : { signal }), }); - const value = result.ok ? result.value : cliError(result.error); - if ( - output !== undefined && - (await output.output.write(value, { - command: output.command, - format: output.format, - duration: `${Math.round(performance.now() - started)}ms`, - })) - ) - // Keep failures visible to command logging after the stream has handled stdout. - return result.ok ? undefined : value; - return value; + return result.ok ? result.value : cliError(result.error); }; const cliError = ( diff --git a/src/cli/jsonOutput.ts b/src/cli/jsonOutput.ts index 93df9abd3..b42bd82bd 100644 --- a/src/cli/jsonOutput.ts +++ b/src/cli/jsonOutput.ts @@ -10,7 +10,7 @@ export const writeJsonOutput = async ( destination: Writable, format: JsonOutputFormat = "json", ): Promise => { - for (const part of bufferedJsonParts(documentParts(value, format))) + for (const part of bufferedJsonParts(jsonOutputParts(value, format))) await writePart(destination, part); }; @@ -35,7 +35,8 @@ const writePart = (destination: Writable, part: string): Promise => } }); -function* documentParts( +/** The exact formatted document, including its final newline. */ +export function* jsonOutputParts( value: unknown, format: JsonOutputFormat, ): Generator { diff --git a/src/cli/streamedJsonOutput.ts b/src/cli/streamedJsonOutput.ts index 282316d0a..64977c22d 100644 --- a/src/cli/streamedJsonOutput.ts +++ b/src/cli/streamedJsonOutput.ts @@ -1,10 +1,16 @@ +import { constants } from "node:buffer"; import { type Writable } from "node:stream"; -import { Filter } from "incur"; +import { Cli, Filter } from "incur"; import { parseCliOutputArguments } from "../cliOutput.js"; -import type { JsonValue } from "../domain/jsonValue.js"; -import { writeJsonOutput } from "./jsonOutput.js"; +import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; +import { + projectAnalysisError, + type AnalysisErrorProjection, +} from "../domain/analysisErrorProjection.js"; +import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js"; +import type { CliInstance } from "./types.js"; /** Result metadata supplied by the command that actually ran. */ export interface CliResultOutputMetadata { @@ -17,15 +23,82 @@ export interface CliResultOutputMetadata { export interface CliResultOutput { readonly handled: boolean; readonly failed: boolean; - write(value: JsonValue, metadata: CliResultOutputMetadata): Promise; + readonly error: AnalysisErrorProjection | undefined; + write(value: unknown, metadata: CliResultOutputMetadata): Promise; } -/** Selected command output context, independent of application workflows. */ -export interface CliCommandOutput { - readonly output: CliResultOutput; - readonly command: string; - readonly format: string; -} +type CommandMap = NonNullable>; +type CommandDefinition = Extract< + CommandMap extends Map ? Entry : never, + { run: unknown } +>; +const registeredCommands: WeakMap = Cli.toCommands; + +/** Install formatting once, after registration, for every ordinary CLI result. */ +export const streamCliCommandResults = ( + cli: CliInstance, + output: CliResultOutput, +): void => { + const commands = registeredCommands.get(cli); + if (commands !== undefined) wrapCommands(commands, [], output); +}; + +const wrapCommands = ( + commands: CommandMap, + parents: readonly string[], + output: CliResultOutput, +): void => { + for (const [name, entry] of commands) { + const path = [...parents, name]; + if ("_group" in entry) { + wrapCommands(entry.commands, path, output); + if (entry.root !== undefined) + wrapCommand(entry.root, path.join(" "), output); + } else if (!("_alias" in entry) && !("_fetch" in entry)) + wrapCommand(entry, path.join(" "), output); + } +}; + +const wrapCommand = ( + command: Pick, + name: string, + output: CliResultOutput, +): void => { + const run = command.run; + command.run = (context) => { + const started = performance.now(); + const result: unknown = run(context); + // Generator results and Incur's sentinel responses retain their own protocol. + if ( + typeof result === "object" && + result !== null && + Symbol.asyncIterator in result + ) + return result; + return Promise.resolve(result).then(async (value: unknown) => { + if ( + typeof value === "object" && + value !== null && + Symbol.for("incur.sentinel") in value + ) + return value; + if ( + !(await output.write(value, { + command: name, + format: context.format, + duration: `${Math.round(performance.now() - started)}ms`, + })) + ) + return value; + if (output.error !== undefined) + return context.error({ + code: output.error.code, + message: output.error.message, + }); + return undefined; + }); + }; +}; /** Preserve Incur's JSON controls while streaming the complete result. */ export const createStreamedCliJsonOutput = ( @@ -35,7 +108,6 @@ export const createStreamedCliJsonOutput = ( const options = parseCliOutputArguments(arguments_); if ( options.parseError || - options.tokenCount || options.tokenWindow || (options.format !== "json" && options.format !== "jsonl") ) @@ -43,6 +115,7 @@ export const createStreamedCliJsonOutput = ( const format = options.format; let handled = false; let failed = false; + let error: AnalysisErrorProjection | undefined; return { get handled() { return handled; @@ -50,6 +123,9 @@ export const createStreamedCliJsonOutput = ( get failed() { return failed; }, + get error() { + return error; + }, async write(value, metadata) { if (metadata.format !== format) return false; const filtered: unknown = options.filterOutput @@ -59,6 +135,36 @@ export const createStreamedCliJsonOutput = ( command: metadata.command, duration: metadata.duration, }; + if (options.tokenCount) { + // Incur/tokenx materialize the formatted value. Measure its UTF-16 + // expansion before allowing that allocation, independently of UTF-8 bytes. + let characters = 0; + if ( + filtered !== undefined && + filtered !== null && + typeof filtered !== "function" && + typeof filtered !== "symbol" + ) + for (const part of jsonOutputParts(filtered, format)) + characters += part.length; + characters = Math.max(0, characters - 1); + if (characters <= constants.MAX_STRING_LENGTH) return false; + error = projectAnalysisError( + new AnalysisResourceConstraintError( + metadata.command, + "memory", + "Token counting requires a formatted string larger than the runtime permits.", + { + formatted_characters: characters, + max_string_characters: constants.MAX_STRING_LENGTH, + }, + { + remediationAction: + "Remove --token-count to stream the complete JSON result, or narrow it with --filter-output.", + }, + ), + ); + } const document = options.fullOutput ? filtered === undefined ? { ok: true, meta } @@ -73,7 +179,15 @@ export const createStreamedCliJsonOutput = ( // document from Incur's error formatter. handled = true; try { - await writeJsonOutput(document, destination, format); + await writeJsonOutput( + error === undefined + ? document + : options.fullOutput + ? { ok: false, error, meta } + : error, + destination, + format, + ); } catch (cause: unknown) { failed = true; throw cause; diff --git a/tests/acceptance/managedCliOutput.test.ts b/tests/acceptance/managedCliOutput.test.ts new file mode 100644 index 000000000..84cec5222 --- /dev/null +++ b/tests/acceptance/managedCliOutput.test.ts @@ -0,0 +1,62 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect } from "vitest"; + +import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { cliTest } from "../support/cli/cliFixture.js"; + +cliTest( + "managed CLI preserves evidence, filters, envelopes, and bounded token counts", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-managed-cli-output-"); + const path = join(root, "fixture.dll"); + await writeFile(path, buildManagedPeFixture()); + const argv = ["inspect-managed-members", path, "--json"]; + const result = await cli.run({ arguments: argv }); + expect(result.exitCode).toBe(0); + expect(result.json).toMatchObject({ + operation: "inspect_managed_members", + provider: { id: "rea-dotnet-static" }, + subject: { local_path: path }, + normalized_result: { + methods: [expect.objectContaining({ token: expect.any(String) })], + }, + }); + const filtered = await cli.run({ + arguments: [...argv, "--filter-output", "operation", "--full-output"], + }); + expect(filtered.exitCode).toBe(0); + expect(filtered.json).toMatchObject({ + ok: true, + data: "inspect_managed_members", + meta: { + command: "inspect-managed-members", + duration: expect.stringMatching(/^\d+ms$/u), + }, + }); + const count = await cli.run({ + arguments: [...argv, "--filter-output", "operation", "--token-count"], + }); + expect(count.exitCode).toBe(0); + expect(count.stdout).toMatch(/^\d+\n$/u); + const omittedCount = await cli.run({ + arguments: [...argv, "--filter-output", "toString", "--token-count"], + }); + expect(omittedCount.exitCode).toBe(0); + expect(omittedCount.stdout).toBe("0\n"); + const jsonl = await cli.run({ + arguments: [ + "inspect-managed-members", + path, + "--format", + "jsonl", + "--filter-output", + "operation", + ], + }); + expect(jsonl.exitCode).toBe(0); + expect(jsonl.json).toBe("inspect_managed_members"); + }, +); diff --git a/tests/boundary/cli/jsonOutput.test.ts b/tests/boundary/cli/jsonOutput.test.ts index 7c1ff4ddd..029407388 100644 --- a/tests/boundary/cli/jsonOutput.test.ts +++ b/tests/boundary/cli/jsonOutput.test.ts @@ -1,9 +1,17 @@ +import { constants } from "node:buffer"; +import { createHash } from "node:crypto"; import { Writable } from "node:stream"; +import { Cli } from "incur"; import { describe, expect, it } from "vitest"; import { writeJsonOutput } from "../../../src/cli/jsonOutput.js"; -import { createStreamedCliJsonOutput } from "../../../src/cli/streamedJsonOutput.js"; +import { + createStreamedCliJsonOutput, + streamCliCommandResults, +} from "../../../src/cli/streamedJsonOutput.js"; +import { registerManagedCommands } from "../../../src/cli/managedCommands.js"; +import { silentLogger } from "../../../src/logger.js"; const collect = async ( value: unknown, @@ -140,7 +148,6 @@ describe("streamed CLI result surface", () => { it.each([ [], ["--format", "md"], - ["--json", "--token-count"], ["--json", "--token-limit", "5"], ["--json", "--format", "invalid"], ])("delegates unsupported output controls %j", (...arguments_) => { @@ -167,4 +174,104 @@ describe("streamed CLI result surface", () => { expect(output.handled).toBe(true); expect(output.failed).toBe(true); }); + + it("streams managed command output past the engine string limit and declines oversized token counting", async () => { + const leaf = "x".repeat(64 * 1024); + const count = Math.ceil(constants.MAX_STRING_LENGTH / leaf.length) + 1; + const value = { methods: Array.from({ length: count }, () => leaf) }; + const expected = createHash("sha256"); + const encodedLeaf = JSON.stringify(leaf); + const prefix = '{\n "methods": [\n '; + const separator = ",\n "; + const suffix = "\n ]\n}\n"; + expected.update(prefix); + for (let index = 0; index < count; index += 1) { + if (index > 0) expected.update(separator); + expected.update(encodedLeaf); + } + expected.update(suffix); + const expectedCharacters = + prefix.length + + count * encodedLeaf.length + + (count - 1) * separator.length + + suffix.length; + expect(expectedCharacters).toBeGreaterThan(constants.MAX_STRING_LENGTH); + + const actual = createHash("sha256"); + let bytes = 0; + const destination = new Writable({ + write(chunk: Buffer, _encoding, callback) { + bytes += chunk.length; + actual.update(chunk); + callback(); + }, + }); + const cli = Cli.create("rea-output-test", { sync: false }); + registerManagedCommands(cli, silentLogger, async (path, operation) => { + expect(path).toBe("fixture.dll"); + expect(operation).toBe("inspect_managed_members"); + return value; + }); + const argv = ["inspect-managed-members", "fixture.dll", "--json"]; + const output = createStreamedCliJsonOutput(argv, destination); + if (output === undefined) throw new Error("Missing JSON output surface"); + streamCliCommandResults(cli, output); + let exitCode = 0; + let fallbackBytes = 0; + await cli.serve(argv, { + stdout: (text) => { + if (!output.handled) fallbackBytes += text.length; + }, + exit: (code) => { + exitCode = code; + }, + }); + expect(exitCode).toBe(0); + expect(fallbackBytes).toBe(0); + expect(bytes).toBe(expectedCharacters); + expect(actual.digest("hex")).toBe(expected.digest("hex")); + + const chunks: Buffer[] = []; + const tokenArgv = [...argv, "--token-count", "--full-output"]; + const tokenOutput = createStreamedCliJsonOutput( + tokenArgv, + new Writable({ + write(chunk: Buffer, _encoding, callback) { + chunks.push(chunk); + callback(); + }, + }), + ); + if (tokenOutput === undefined) + throw new Error("Missing token-count output surface"); + const tokenCli = Cli.create("rea-output-test", { sync: false }); + registerManagedCommands(tokenCli, silentLogger, async () => value); + streamCliCommandResults(tokenCli, tokenOutput); + await tokenCli.serve(tokenArgv, { + stdout: (text) => { + if (!tokenOutput.handled) fallbackBytes += text.length; + }, + exit: (code) => { + exitCode = code; + }, + }); + expect(exitCode).toBe(1); + expect(fallbackBytes).toBe(0); + expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({ + ok: false, + error: { + code: "resource_constraint", + remediation: { + action: expect.stringContaining("Remove --token-count"), + }, + details: { + reported_limits: { + formatted_characters: expectedCharacters - 1, + max_string_characters: constants.MAX_STRING_LENGTH, + }, + }, + }, + meta: { command: "inspect-managed-members" }, + }); + }, 60_000); }); From 037709a52c0824f4d2bbee90d8e2642b2d88d364 Mon Sep 17 00:00:00 2001 From: keemsisi Date: Fri, 9 Oct 2026 23:34:21 +0100 Subject: [PATCH 114/189] perf(javascript): validate the version change graph once (#1370) compareJavaScriptApplicationVersions built the change graph with createJavaScriptApplicationGraph, which validates it and re-derives every node, observation, edge and graph ID, then parsed the result with a schema that embeds the full graph schema, repeating all of that work. Seal the change graph with the owned immutable factory and accept that exact sealed graph in the result parse, as owned analysis results already do. Items, coverage and the public result schema are unchanged; output is byte-identical. --- .../javascriptApplicationChangeGraph.ts | 8 +- ...scriptApplicationVersionComparison.test.ts | 140 ++++++++++++++++++ .../javascriptApplicationVersionComparison.ts | 4 +- ...riptApplicationVersionComparisonSchemas.ts | 14 +- 4 files changed, 160 insertions(+), 6 deletions(-) create mode 100644 src/domain/javascript/javascriptApplicationVersionComparison.test.ts diff --git a/src/domain/javascript/javascriptApplicationChangeGraph.ts b/src/domain/javascript/javascriptApplicationChangeGraph.ts index ce0e136b3..4c80b3204 100644 --- a/src/domain/javascript/javascriptApplicationChangeGraph.ts +++ b/src/domain/javascript/javascriptApplicationChangeGraph.ts @@ -1,6 +1,6 @@ import { createJavaScriptApplicationEdge, - createJavaScriptApplicationGraph, + createImmutableJavaScriptApplicationGraphSteps, createJavaScriptApplicationNode, type JavaScriptApplicationGraph, } from "./javascriptApplicationGraph.js"; @@ -59,7 +59,7 @@ export const buildJavaScriptApplicationChangeGraph = ( const candidateEdges = uniqueEdges([...sourceEdges, ...comparisonEdges]); const rootNodeIds = preferredRoots.filter((nodeId) => retained.has(nodeId)); const fallbackRoot = mergedNodes[0]?.node_id; - const graph = createJavaScriptApplicationGraph({ + const steps = createImmutableJavaScriptApplicationGraphSteps({ schema: "JavaScriptApplicationGraph", root_node_ids: rootNodeIds.length > 0 @@ -77,7 +77,9 @@ export const buildJavaScriptApplicationChangeGraph = ( "The change graph contains compared entities and their retained relationships; it is not an executable application.", ]), }); - return { graph }; + let next = steps.next(); + while (!next.done) next = steps.next(); + return { graph: next.value }; }; const nodeCandidates = ( diff --git a/src/domain/javascript/javascriptApplicationVersionComparison.test.ts b/src/domain/javascript/javascriptApplicationVersionComparison.test.ts new file mode 100644 index 000000000..c0d92cc38 --- /dev/null +++ b/src/domain/javascript/javascriptApplicationVersionComparison.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; + +import { + createJavaScriptApplicationEdge, + createJavaScriptApplicationGraph, + createJavaScriptApplicationNode, + isValidatedImmutableJavaScriptApplicationGraph, + parseJavaScriptApplicationGraph, + type JavaScriptApplicationGraph, +} from "./javascriptApplicationGraph.js"; +import { + artifactEvidence, + completeCoverage, +} from "./javascriptApplicationGraph.fixture.js"; +import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js"; +import { + applicationVersionComparisonResultSchema, + ownedApplicationVersionComparisonResultSchema, +} from "./javascriptApplicationVersionComparisonSchemas.js"; + +const LEFT_SHA = "a".repeat(64); +const RIGHT_SHA = "b".repeat(64); + +const buildGraph = ( + artifactSha: string, + version: number, +): JavaScriptApplicationGraph => { + const nodes = ["a", "b", "c"].map((name) => + createJavaScriptApplicationNode({ + kind: "javascript-module", + identity: { + strategy: "canonical-path", + stability: "artifact-version", + artifact_sha256: artifactSha, + path: `${name}.js`, + }, + observations: [ + { + label: `${name}.js`, + properties: { + structural_fingerprint_sha256: name + .charCodeAt(0) + .toString(16) + .padStart(64, "0"), + structural_fingerprint_algorithm: "fixture", + source_sha256: (name === "b" ? version : 0) + .toString(16) + .padStart(64, "0"), + }, + evidence: artifactEvidence(artifactSha, `${name}.js`), + }, + ], + }), + ); + const [a, b, c] = nodes; + if (a === undefined || b === undefined || c === undefined) + throw new Error("Missing fixture node"); + return createJavaScriptApplicationGraph({ + schema: "JavaScriptApplicationGraph", + root_node_ids: [a.node_id], + nodes, + edges: [ + createJavaScriptApplicationEdge({ + source_node_id: a.node_id, + target_node_id: b.node_id, + relation: "imports", + properties: {}, + evidence: artifactEvidence(artifactSha, "a.js"), + }), + createJavaScriptApplicationEdge({ + source_node_id: b.node_id, + target_node_id: c.node_id, + relation: "imports", + properties: {}, + evidence: artifactEvidence(artifactSha, "b.js"), + }), + ], + coverage: completeCoverage, + limitations: [], + }); +}; + +const compare = () => + compareJavaScriptApplicationVersions({ + left: { + evidenceId: `ev_${"1".repeat(64)}`, + rootArtifactSha256: LEFT_SHA, + graph: buildGraph(LEFT_SHA, 1), + }, + right: { + evidenceId: `ev_${"2".repeat(64)}`, + rootArtifactSha256: RIGHT_SHA, + graph: buildGraph(RIGHT_SHA, 2), + }, + leftNativeEvidence: [], + rightNativeEvidence: [], + }); + +describe("application version comparison result", () => { + it("returns a sealed change graph that passes complete validation", () => { + const result = compare(); + expect( + result.graph.edges.some(({ relation }) => relation === "changed_from"), + ).toBe(true); + expect(isValidatedImmutableJavaScriptApplicationGraph(result.graph)).toBe( + true, + ); + expect(Object.isFrozen(result.graph.edges)).toBe(true); + expect(parseJavaScriptApplicationGraph(result.graph)).toEqual(result.graph); + expect(applicationVersionComparisonResultSchema.parse(result)).toEqual( + result, + ); + }); + + it("does not reuse a change graph without an owned proof", () => { + const result = compare(); + const copy = structuredClone(result.graph); + expect(isValidatedImmutableJavaScriptApplicationGraph(copy)).toBe(false); + expect(() => + ownedApplicationVersionComparisonResultSchema.parse({ + ...result, + graph: copy, + }), + ).toThrow(); + expect( + applicationVersionComparisonResultSchema.parse({ ...result, graph: copy }) + .graph, + ).toEqual(result.graph); + }); + + it("keeps coverage validation for owned results", () => { + const result = compare(); + expect(() => + ownedApplicationVersionComparisonResultSchema.parse({ + ...result, + coverage: { ...result.coverage, status: "partial" }, + }), + ).toThrow("Comparison coverage must match source graph completeness"); + }); +}); diff --git a/src/domain/javascript/javascriptApplicationVersionComparison.ts b/src/domain/javascript/javascriptApplicationVersionComparison.ts index 50f82c335..be60d067a 100644 --- a/src/domain/javascript/javascriptApplicationVersionComparison.ts +++ b/src/domain/javascript/javascriptApplicationVersionComparison.ts @@ -3,7 +3,7 @@ import { uniqueSorted } from "../canonicalOrdering.js"; import type { Evidence } from "../evidence.js"; import { buildJavaScriptApplicationChangeGraph } from "./javascriptApplicationChangeGraph.js"; import { - applicationVersionComparisonResultSchema, + ownedApplicationVersionComparisonResultSchema, type ApplicationVersionComparisonResult, } from "./javascriptApplicationVersionComparisonSchemas.js"; import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js"; @@ -76,7 +76,7 @@ export const compareJavaScriptApplicationVersions = ( evidence_links: evidenceLinks, limitations: comparisonLimitations(input), }; - return applicationVersionComparisonResultSchema.parse({ + return ownedApplicationVersionComparisonResultSchema.parse({ ...semantic, comparison_id: `javc_${digestCanonicalValue(semantic, "Application version comparison")}`, }); diff --git a/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts b/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts index 309c95c89..d9d54449e 100644 --- a/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts +++ b/src/domain/javascript/javascriptApplicationVersionComparisonSchemas.ts @@ -2,7 +2,11 @@ import { z } from "zod"; import { emptyArraySchema } from "../emptyArraySchema.js"; import { evidenceSchema } from "../evidence.js"; -import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js"; +import { + isValidatedImmutableJavaScriptApplicationGraph, + javascriptApplicationGraphSchema, + type JavaScriptApplicationGraph, +} from "./javascriptApplicationGraph.js"; import { JAVASCRIPT_APPLICATION_NODE_KINDS } from "./javascriptApplicationGraphSchemas.js"; import { prefixedDigestSchema } from "../digests.js"; @@ -234,6 +238,14 @@ export const applicationVersionComparisonResultSchema = z }); }); +/** Reuse the exact owned change graph while validating the rest of the result. */ +export const ownedApplicationVersionComparisonResultSchema = + applicationVersionComparisonResultSchema.safeExtend({ + graph: z.custom( + isValidatedImmutableJavaScriptApplicationGraph, + ), + }); + export type ApplicationVersionComparisonItem = z.infer< typeof comparisonItemSchema >; From f91f2798b4dc6adb61b3ffe28a24a5d55adbd6ff Mon Sep 17 00:00:00 2001 From: You Wish <29498139+Y0UW1SH@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:36:35 -0400 Subject: [PATCH 115/189] fix(process): keep unobserved file contents unknown (#1358) --- .../capture/FilesystemCoverage.test.ts | 164 +++++++++++++++++- .../capture/ProcessCaptureLifecycle.ts | 26 ++- .../capture/ProcessFilesystemEffects.ts | 27 ++- .../processFilesystemCoverageAdapters.test.ts | 85 +++++++-- 4 files changed, 267 insertions(+), 35 deletions(-) diff --git a/src/process/capture/FilesystemCoverage.test.ts b/src/process/capture/FilesystemCoverage.test.ts index 36ebfc6de..2eec44bd5 100644 --- a/src/process/capture/FilesystemCoverage.test.ts +++ b/src/process/capture/FilesystemCoverage.test.ts @@ -1,4 +1,11 @@ -import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { + chmod, + mkdir, + readFile, + rm, + symlink, + writeFile, +} from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { parseProcessScenario } from "../../domain/process/processScenario.js"; @@ -126,6 +133,161 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( }, ); +it.each([ + { name: "both", beforeOmitted: true, afterOmitted: true, contents: "after!" }, + { + name: "before", + beforeOmitted: true, + afterOmitted: false, + contents: "after!", + }, + { + name: "after", + beforeOmitted: false, + afterOmitted: true, + contents: "after!", + }, + { + name: "both for an untouched file", + beforeOmitted: true, + afterOmitted: true, + contents: "before", + }, +])( + "keeps content equality unknown when $name snapshots omit its digest", + async ({ beforeOmitted, afterOmitted, contents }) => { + const root = await createTestTempDirectory("rea-fs-content-unknown-"); + const budgetFile = join(root, "a.txt"); + const file = join(root, "b.txt"); + await writeFile(file, "before"); + if (beforeOmitted) await writeFile(budgetFile, "budget"); + const scenario = parseProcessScenario({ + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [root], + limits: { file_bytes: 6 }, + }); + const before = await snapshotRoots(scenario); + if (beforeOmitted && !afterOmitted) await rm(budgetFile); + if (!beforeOmitted && afterOmitted) await writeFile(budgetFile, "budget"); + if (contents !== "before") await writeFile(file, contents); + const after = await snapshotRoots(scenario); + expect(await readFile(file, "utf8")).toBe(contents); + const effect = classifyFilesystemEffects(before, after).find( + ({ path }) => path === "root_0:b.txt", + ); + expect(effect).toMatchObject({ + status: "unknown", + before: { + type: "file", + size: 6, + sha256: beforeOmitted ? null : expect.any(String), + }, + after: { + type: "file", + size: 6, + sha256: afterOmitted ? null : expect.any(String), + }, + reason: expect.stringMatching(/content.*hash|hash.*content/iu), + }); + }, +); + +it("preserves observed content and metadata changes without treating missing hashes as equality", async () => { + const root = await createTestTempDirectory("rea-fs-observed-changes-"); + for (const name of ["changed", "stable", "unhashed", "retyped"]) + await writeFile(join(root, name), "before"); + const scenario = parseProcessScenario({ + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [root], + }); + const before = await snapshotRoots(scenario); + await writeFile(join(root, "changed"), "after!"); + await writeFile(join(root, "unhashed"), "different size"); + await rm(join(root, "retyped")); + await mkdir(join(root, "retyped")); + const after = await snapshotRoots(scenario); + const effects = classifyFilesystemEffects(before, after); + expect(effects.find(({ path }) => path === "root_0:changed")?.status).toBe( + "modified", + ); + expect(effects.find(({ path }) => path === "root_0:stable")?.status).toBe( + "unchanged", + ); + expect(effects.find(({ path }) => path === "root_0:retyped")?.status).toBe( + "modified", + ); + const noHashes = parseProcessScenario({ + ...scenario, + limits: { file_bytes: 1 }, + }); + const unhashedBefore = await snapshotRoots(noHashes); + await writeFile(join(root, "unhashed"), "size changed again"); + const unhashedAfter = await snapshotRoots(noHashes); + expect( + classifyFilesystemEffects(unhashedBefore, unhashedAfter).find( + ({ path }) => path === "root_0:unhashed", + ), + ).toMatchObject({ + status: "modified", + before: { sha256: null }, + after: { sha256: null }, + }); +}); + +it.skipIf(process.platform === "win32")( + "preserves an observed permission change when file digests are omitted", + async () => { + const root = await createTestTempDirectory("rea-fs-mode-change-"); + const file = join(root, "file"); + await writeFile(file, "before", { mode: 0o600 }); + const scenario = parseProcessScenario({ + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [file], + limits: { file_bytes: 1 }, + }); + const before = await snapshotRoots(scenario); + await chmod(file, 0o644); + const after = await snapshotRoots(scenario); + expect(classifyFilesystemEffects(before, after)).toMatchObject([ + { status: "modified", before: { sha256: null }, after: { sha256: null } }, + ]); + }, +); + +it.skipIf(process.platform === "win32")( + "compares directories and symlink targets without requiring file content hashes", + async () => { + const root = await createTestTempDirectory("rea-fs-nonfile-effects-"); + await mkdir(join(root, "empty")); + await writeFile(join(root, "a.txt"), "before"); + await writeFile(join(root, "b.txt"), "unused"); + await symlink("a.txt", join(root, "stable-link")); + await symlink("a.txt", join(root, "moved-link")); + const scenario = parseProcessScenario({ + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [root], + limits: { file_bytes: 1 }, + }); + const before = await snapshotRoots(scenario); + await writeFile(join(root, "a.txt"), "after!"); + await rm(join(root, "moved-link")); + await symlink("b.txt", join(root, "moved-link")); + const after = await snapshotRoots(scenario); + const effects = classifyFilesystemEffects(before, after); + for (const name of ["empty", "stable-link"]) + expect( + effects.find(({ path }) => path === `root_0:${name}`)?.status, + ).toBe("unchanged"); + expect( + effects.find(({ path }) => path === "root_0:moved-link")?.status, + ).toBe("modified"); + }, +); + it("preserves creation when the selected root was observed missing before capture", async () => { const root = await createTestTempDirectory("rea-fs-missing-root-"); const file = join(root, "created.txt"); diff --git a/src/process/capture/ProcessCaptureLifecycle.ts b/src/process/capture/ProcessCaptureLifecycle.ts index af439e9dd..17d262fa7 100644 --- a/src/process/capture/ProcessCaptureLifecycle.ts +++ b/src/process/capture/ProcessCaptureLifecycle.ts @@ -250,11 +250,13 @@ export const buildCaptureResult = ( options.before, options.after, ); - const hasUnknownFilesystemEffects = filesystemEffects.some( - ({ status }) => status === "unknown", - ); - const incompleteFilesystemUnknown = - "Path absence in incomplete enumeration or below an unfollowed symbolic link remains unknown."; + const filesystemUnknowns = [ + ...new Set( + filesystemEffects.flatMap((effect) => + effect.status === "unknown" ? [effect.reason] : [], + ), + ), + ]; return { manifest: options.manifest, normalization: options.scenario.normalization, @@ -291,7 +293,7 @@ export const buildCaptureResult = ( "Filesystem observations are before/after snapshots, not syscall traces.", "Inherited host environment variables are not recorded and may affect results.", ...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []), - ...(hasUnknownFilesystemEffects ? [incompleteFilesystemUnknown] : []), + ...filesystemUnknowns, ...captureCoverageUnknowns(options.truncationDetails).map( ({ reason }) => reason, ), @@ -324,14 +326,10 @@ export const buildCaptureResult = ( }, ] : []), - ...(hasUnknownFilesystemEffects - ? [ - { - scope: "filesystem" as const, - reason: incompleteFilesystemUnknown, - }, - ] - : []), + ...filesystemUnknowns.map((reason) => ({ + scope: "filesystem" as const, + reason, + })), ...(hasSensitiveScriptedInput ? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }] : []), diff --git a/src/process/capture/ProcessFilesystemEffects.ts b/src/process/capture/ProcessFilesystemEffects.ts index 97ae578c4..af67d4cee 100644 --- a/src/process/capture/ProcessFilesystemEffects.ts +++ b/src/process/capture/ProcessFilesystemEffects.ts @@ -29,7 +29,7 @@ const unobservedAbsenceReason = ( return undefined; }; -/** Classify effects only when a snapshot establishes the missing path's absence. */ +/** Classify effects only from observed path absence, metadata, and content hashes. */ export const classifyFilesystemEffects = ( before: ProcessFilesystemSnapshot, after: ProcessFilesystemSnapshot, @@ -84,12 +84,31 @@ export const classifyFilesystemEffects = ( before: beforeFile, after: null, } as const; + const metadataChanged = + beforeFile.type !== afterFile.type || + beforeFile.mode !== afterFile.mode || + beforeFile.size !== afterFile.size || + beforeFile.symlink_target !== afterFile.symlink_target; + if ( + !metadataChanged && + beforeFile.type === "file" && + afterFile.type === "file" && + (beforeFile.sha256 === null || afterFile.sha256 === null) + ) + return { + path, + status: "unknown", + before: beforeFile, + after: afterFile, + reason: + "A file content hash is unavailable in at least one snapshot; matching metadata does not establish unchanged contents.", + } as const; return { path, status: - JSON.stringify(beforeFile) === JSON.stringify(afterFile) - ? "unchanged" - : "modified", + metadataChanged || beforeFile.sha256 !== afterFile.sha256 + ? "modified" + : "unchanged", before: beforeFile, after: afterFile, } as const; diff --git a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts index aa537514f..ec7ce5b4c 100644 --- a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts +++ b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts @@ -17,6 +17,22 @@ import { const exec = promisify(execFile); +const captureViaCli = async (scenario: Record) => { + const scenarioPath = join( + await createTestTempDirectory("rea-fs-scenario-"), + "scenario.json", + ); + await writeFile(scenarioPath, JSON.stringify(scenario)); + const { stdout } = await exec(process.execPath, [ + "scripts/rea.mjs", + "capture-process", + scenarioPath, + "--format", + "json", + ]); + return parseEvidence(JSON.parse(stdout)); +}; + const captureViaMcp = async (scenario: Record) => { const session = createTestBinarySession(() => { throw new Error("Process capture must not launch a binary provider"); @@ -54,22 +70,9 @@ itWithCaptureCapability.each(["cli", "mcp"] as const)( filesystem_observation_paths: [root], limits: { files: 2 }, }; - let evidence; - if (adapter === "cli") { - const scenarioPath = join( - await createTestTempDirectory("rea-fs-scenario-"), - "scenario.json", - ); - await writeFile(scenarioPath, JSON.stringify(scenario)); - const { stdout } = await exec(process.execPath, [ - "scripts/rea.mjs", - "capture-process", - scenarioPath, - "--format", - "json", - ]); - evidence = parseEvidence(JSON.parse(stdout)); - } else evidence = await captureViaMcp(scenario); + const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)( + scenario, + ); const capture = parseProcessCapture(evidence.normalized_result); expect(capture.truncated).toBe(true); expect(await readFile(join(root, "z.txt"), "utf8")).toBe("unchanged"); @@ -86,6 +89,56 @@ itWithCaptureCapability.each(["cli", "mcp"] as const)( 20_000, ); +itWithCaptureCapability.each(["cli", "mcp"] as const)( + "reports unknown content after a same-size rewrite without digests through %s", + async (adapter) => { + const root = await createTestTempDirectory("rea-fs-content-adapter-"); + const file = join(root, "changed.txt"); + await writeFile(file, "before"); + const scenario = { + executable: process.execPath, + arguments: [ + "-e", + "require('node:fs').writeFileSync('changed.txt','after!')", + ], + working_directory: root, + filesystem_observation_paths: [root], + limits: { file_bytes: 1 }, + }; + const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)( + scenario, + ); + const capture = parseProcessCapture(evidence.normalized_result); + expect(await readFile(file, "utf8")).toBe("after!"); + const effect = capture.filesystem_effects.find( + ({ path }) => path === "root_0:changed.txt", + ); + expect(effect).toMatchObject({ + status: "unknown", + reason: expect.any(String), + before: { size: 6, sha256: null }, + after: { size: 6, sha256: null }, + }); + if (effect?.status !== "unknown") + throw new Error("Expected unknown file contents"); + expect( + capture.filesystem_checkpoints.find( + ({ name }) => name === "after_settlement", + )?.effects, + ).toContainEqual(effect); + expect(capture.residual_unknowns).toContainEqual({ + scope: "filesystem", + reason: effect.reason, + }); + expect(capture.limitations).toContain(effect.reason); + expect( + capture.truncation_details.filesystem_after.enumeration_truncated, + ).toBe(false); + expect(compareProcessCaptures(capture, capture).filesystem).toBe("unknown"); + }, + 20_000, +); + it.skipIf(CAPTURE_SKIP_REASON || process.platform === "win32")( "keeps unfollowed descendant absence unknown through MCP Evidence and comparison", async () => { From f504c2a351027f17ac353fba2d7cfc3505ee17d6 Mon Sep 17 00:00:00 2001 From: yi111 <153097222+Yi-111-a@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:38:47 +0800 Subject: [PATCH 116/189] fix(javascript): decline source-map UNC references with an unusable host (#1372) * fix(javascript): decline source-map UNC references with an unusable host A source map can name a Windows share whose host a file URL cannot carry, such as `\\bad host\share\a.js`. On the Node builds `engines` admits, `pathToFileURL(path, { windows: true })` fails a native assertion and calls `abort()` on Node 22.19-22.22, 24.11-24.15 and 26.0, so the process dies with exit 134 instead of declining the reference. Node 22.23 and 24.16 raise `ERR_INVALID_URL` instead, and older builds silently drop the host, so the same reference resolves three different ways depending on the runtime. Validate the UNC host before handing the path to Node. A host carrying a forbidden host code point, a percent escape or nothing at all now resolves as `unresolved` on every admitted build, and `npm test` passes the existing `\\bad host\share\a.js` row everywhere. Well-formed UNC hosts and drive-letter paths are untouched. * fix(javascript): validate UNC hosts through IDNA before conversion Reject Unicode source-map UNC hosts that URL/IDNA processing cannot use or normalizes to an empty hostname before calling Windows pathToFileURL. Keep the original source identity and preserve usable normalized hosts. Exercise the built reference resolver in owned subprocesses, including U+00AD and U+200C as source names and source roots. The original PR implementation aborts under Node 22.22.2; the new regression isolates those signals from the test runner. Add this test to the existing Node 22 Windows CI step. Validation: 64 focused tests pass on Node 22.22.2 and 24.18.0; npm run check and test discovery pass. Local verification ran on macOS; Windows verification remains with CI. --------- Co-authored-by: Yi-111-a Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- .github/workflows/ci.yml | 3 +- .../javascript/javascriptSourceMapPaths.ts | 17 +++- .../process/sourceMapUncHosts.test.ts | 92 +++++++++++++++++++ 3 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 tests/boundary/process/sourceMapUncHosts.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6755bb04c..503d44f16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -460,12 +460,13 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22.19.0 - - name: Verify native directory identity on Node 22 + - name: Verify native path boundaries on Node 22 run: >- npx vitest run --coverage.enabled=false tests/boundary/filesystem/directoryArtifactReaderOpen.test.ts tests/boundary/filesystem/javascriptPackagePrecedence.test.ts tests/boundary/filesystem/javascriptArtifactContentIdentity.test.ts + tests/boundary/process/sourceMapUncHosts.test.ts - uses: actions/upload-artifact@v4 if: always() with: diff --git a/src/domain/javascript/javascriptSourceMapPaths.ts b/src/domain/javascript/javascriptSourceMapPaths.ts index 33e59454f..d897bdd26 100644 --- a/src/domain/javascript/javascriptSourceMapPaths.ts +++ b/src/domain/javascript/javascriptSourceMapPaths.ts @@ -1,5 +1,5 @@ import { posix } from "node:path"; -import { fileURLToPath, pathToFileURL } from "node:url"; +import { domainToASCII, fileURLToPath, pathToFileURL } from "node:url"; import { z } from "zod"; @@ -101,7 +101,22 @@ const resolveJavaScriptSourceMapPath = ( return { path: value, kind: relative ? "artifact-relative" : "suffix" }; }; +// Reject URL delimiters/escapes before IDNA can truncate or decode the host. +const unusableHost = /[\0\t\n\r #/:<>?@[\\\]^|%]/u; + +// URL/IDNA validation also rejects Unicode hosts that normalize to empty. +const carriesUsableHost = (host: string): boolean => + !unusableHost.test(host) && domainToASCII(host) !== ""; + const windowsFileUrl = (path: string): URL | null => { + // A malformed UNC host aborts pathToFileURL() on the Node builds this + // package admits, so decline the reference before handing the path over + // rather than trusting a TypeError that never arrives. + if ( + path.startsWith("\\\\") && + !carriesUsableHost(path.slice(2).split("\\")[0] ?? "") + ) + return null; try { return pathToFileURL(path, { windows: true }); } catch (cause: unknown) { diff --git a/tests/boundary/process/sourceMapUncHosts.test.ts b/tests/boundary/process/sourceMapUncHosts.test.ts new file mode 100644 index 000000000..293a3f71a --- /dev/null +++ b/tests/boundary/process/sourceMapUncHosts.test.ts @@ -0,0 +1,92 @@ +import { expect } from "vitest"; + +import { processTest } from "../../support/process/processFixture.js"; + +const cases = [ + { + name: "soft hyphen U+00AD", + source: "\\\\\u00ad\\share\\source.ts", + expected: { kind: "unresolved" }, + }, + { + name: "zero width non joiner U+200C", + source: "\\\\\u200c\\share\\source.ts", + expected: { kind: "unresolved" }, + }, + { + name: "ASCII delimiter", + source: "\\\\bad#host\\share\\source.ts", + expected: { kind: "unresolved" }, + }, + { + name: "empty host", + source: "\\\\\\share\\source.ts", + expected: { kind: "unresolved" }, + }, + { + name: "normal host", + source: "\\\\server\\share\\source.ts", + expected: { kind: "suffix", path: "server/share/source.ts" }, + }, + { + name: "valid IDNA host", + source: "\\\\bücher.example\\share\\source.ts", + expected: { kind: "suffix", path: "bücher.example/share/source.ts" }, + }, + { + name: "nonempty normalized host", + source: "\\\\\u00adserver\\share\\source.ts", + expected: { kind: "suffix", path: "server/share/source.ts" }, + }, + { + name: "localhost host", + source: "\\\\localhost\\share\\source.ts", + expected: { kind: "suffix", path: "share/source.ts" }, + }, + { + name: "drive letter", + source: "C:\\src\\source.ts", + expected: { kind: "suffix", path: "C:/src/source.ts" }, + }, + { + name: "soft hyphen source root", + source: "source.ts", + root: "\\\\\u00ad\\share", + expected: { kind: "unresolved" }, + }, + { + name: "zero width non joiner source root", + source: "source.ts", + root: "\\\\\u200c\\share", + expected: { kind: "unresolved" }, + }, +] as const; + +processTest.for(cases)( + "resolves $name in an owned subprocess without a native abort", + async (scenario, { processes }) => { + const sourceRoot = "root" in scenario ? scenario.root : null; + // Import the built production helper in a child. A native assertion must + // become a failed signal assertion here, never terminate the Vitest worker. + const result = await processes.run( + process.execPath, + [ + "--input-type=module", + "--eval", + `import { resolveJavaScriptSourceMapReference } from "./dist/domain/javascript/javascriptSourceMapPaths.js"; + const [source, root] = JSON.parse(process.argv[1]); + console.log(JSON.stringify(resolveJavaScriptSourceMapReference(source, root, "maps/main.js.map")));`, + JSON.stringify([scenario.source, sourceRoot]), + ], + { timeoutMs: 10_000 }, + ); + expect(result.signal, result.stderr).toBeNull(); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + source_name: scenario.source, + source_root: sourceRoot, + map_path: "maps/main.js.map", + resolution: scenario.expected, + }); + }, +); From 1c0cc8a6753b5ac781b28ebb1832f3a6a1771a68 Mon Sep 17 00:00:00 2001 From: You Wish <29498139+Y0UW1SH@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:39:29 -0400 Subject: [PATCH 117/189] fix(snapshot): preserve complete investigation revision histories (#1354) Select residual unknown histories as complete units and retain referenced registry mutation Evidence regardless of the active target at edit time. Prune incompatible dependency histories atomically instead of retaining stale dispositions. Verify public MCP save/read/reopen for verified, withdrawn, and out-of-scope resolutions, and document target scope rules. --- docs/cli.md | 6 + src/domain/evidenceBundle.test.ts | 130 ++++++++++++++++ src/domain/evidenceBundle.ts | 89 ++++++----- .../mcp/workflowSnapshotReplayMcp.test.ts | 143 +++++++++++++++++- 4 files changed, 322 insertions(+), 46 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index a80339cf4..ed5f810e9 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -96,6 +96,12 @@ an exact result when the target bytes, operation, parameters, provider and settings match. Mutations and cursor-dependent calls are excluded from the cache. Snapshot files are local and use owner-only permissions. +Snapshots retain eligible target-scoped question histories in full, including +mutation Evidence recorded while another target was active. Observations and +related questions must still belong to the saved target. If those dependencies +cannot be retained, the entire history is excluded instead of reverting the +question to an earlier revision or disposition. + ```bash rea analyze /absolute/path/to/program --provider ghidra --snapshot /absolute/path/to/analysis/program.json # Repeat the same query to reuse its saved result. diff --git a/src/domain/evidenceBundle.test.ts b/src/domain/evidenceBundle.test.ts index ff6fc38e2..c0a322fe6 100644 --- a/src/domain/evidenceBundle.test.ts +++ b/src/domain/evidenceBundle.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { createEvidence } from "./evidence.js"; +import { ANALYSIS_SNAPSHOT_TARGET } from "./analysisSnapshot.fixture.js"; import { createEvidenceBundle, createImmutableEvidenceBundle, @@ -10,6 +11,7 @@ import { import { createResidualUnknown, recordUnknownInputSchema, + updateResidualUnknown, } from "./residualUnknown.js"; const provider = { id: "fixture", name: "Fixture", version: "1" }; @@ -46,12 +48,140 @@ const makeUnknown = ( }, }); return { + input, evidence: mutation, unknown: createResidualUnknown(input, mutation.evidence_id, scopeDigest), }; }; describe("evidenceBundleForTarget", () => { + it("retains mutation evidence from other targets for complete revision histories", () => { + const first = makeUnknown( + "Target question updated elsewhere", + targetDigest, + ); + const update = createEvidence( + { ...ANALYSIS_SNAPSHOT_TARGET, sha256: foreignDigest }, + provider, + { + predicateType: "rea.residual-unknown-mutation", + operation: "update_unknown", + parameters: { + unknown_id: first.unknown.unknown_id, + expected_revision: 1, + }, + result: { status: "resolved" }, + }, + ); + const resolved = updateResidualUnknown( + first.unknown, + { + ...first.input, + unknown_id: first.unknown.unknown_id, + expected_revision: 1, + status: "resolved", + resolution: { + disposition: "withdrawn", + rationale: "Withdrawn by the analyst", + evidence_ids: [], + }, + }, + update.evidence_id, + ); + const unrelated = makeUnknown("Unrelated foreign question", foreignDigest); + const bundle = parseEvidenceBundle( + createEvidenceBundle( + [first.evidence, update, unrelated.evidence], + [first.unknown, resolved, unrelated.unknown], + ), + ); + const projected = evidenceBundleForTarget(bundle, targetDigest); + expect(parseEvidenceBundle(projected)).toEqual( + createEvidenceBundle([first.evidence, update], [first.unknown, resolved]), + ); + expect(evidenceBundleForTarget(projected, targetDigest)).toEqual(projected); + }); + + it.each(["evidence", "relationship"])( + "removes whole histories and their dependents when a revision requires foreign %s", + (excluded) => { + const first = makeUnknown( + "Target history with an excluded revision", + targetDigest, + ); + const foreign = makeUnknown("Excluded foreign context", foreignDigest); + const evidence = createEvidence( + { ...ANALYSIS_SNAPSHOT_TARGET, sha256: foreignDigest }, + provider, + { operation: "foreign_observation", parameters: {}, result: true }, + ); + const updated = updateResidualUnknown( + first.unknown, + { + ...first.input, + unknown_id: first.unknown.unknown_id, + expected_revision: 1, + status: "investigating", + supporting_evidence_ids: + excluded === "evidence" ? [evidence.evidence_id] : [], + relationships: + excluded === "relationship" + ? [{ type: "related-to", unknown_id: foreign.unknown.unknown_id }] + : [], + resolution: null, + }, + first.evidence.evidence_id, + ); + const resolved = updateResidualUnknown( + updated, + { + ...first.input, + unknown_id: first.unknown.unknown_id, + expected_revision: 2, + status: "resolved", + resolution: { + disposition: "withdrawn", + rationale: "Foreign context removed from the latest revision", + evidence_ids: [], + }, + }, + first.evidence.evidence_id, + ); + const child = makeUnknown( + "Dependent target history", + targetDigest, + first.unknown.unknown_id, + ); + const unrelated = makeUnknown("Independent target history", targetDigest); + const bundle = parseEvidenceBundle( + createEvidenceBundle( + [ + first.evidence, + foreign.evidence, + evidence, + child.evidence, + unrelated.evidence, + ], + [ + first.unknown, + updated, + resolved, + foreign.unknown, + child.unknown, + unrelated.unknown, + ], + ), + ); + expect( + parseEvidenceBundle(evidenceBundleForTarget(bundle, targetDigest)), + ).toEqual( + createEvidenceBundle([unrelated.evidence], [unrelated.unknown]), + ); + }, + ); +}); + +describe("evidenceBundleForTarget relationship pruning", () => { it("removes dependent unknowns when their foreign-scope root is excluded", () => { const foreignRoot = makeUnknown("Foreign root", foreignDigest); const child = makeUnknown( diff --git a/src/domain/evidenceBundle.ts b/src/domain/evidenceBundle.ts index dfedeeb70..217b44fee 100644 --- a/src/domain/evidenceBundle.ts +++ b/src/domain/evidenceBundle.ts @@ -126,7 +126,7 @@ export const createEvidenceBundle = ( }; }; -/** Restrict a bundle to records and complete unknown histories for one artifact. */ +/** Retain target records and eligible complete unknown histories with their mutation evidence. */ export const evidenceBundleForTarget = ( bundle: EvidenceBundle, sha256: string, @@ -134,57 +134,56 @@ export const evidenceBundleForTarget = ( const recordsById = new Map( bundle.records.map((record) => [record.evidence_id, record]), ); - const candidates = bundle.unknowns.filter( - ({ scope_digest: scopeDigest }) => scopeDigest === sha256, - ); - const retained = new Set(); - const revisionsById = new Map(); - const dependents = new Map>(); - for (const unknown of candidates) { - const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids); - const evidenceAvailable = referencedEvidenceIds(unknown).every((id) => { - const record = recordsById.get(id); - return ( - record?.subject?.digest.sha256 === sha256 || - (mutationEvidenceIds.has(id) && - record?.subject === null && - record.predicate_type === "rea.residual-unknown-mutation") - ); + const histories = new Map(); + for (const unknown of bundle.unknowns) { + const history = histories.get(unknown.unknown_id) ?? []; + history.push(unknown); + histories.set(unknown.unknown_id, history); + } + const retained = new Set(); + const dependents = new Map>(); + const relationships = new Map>(); + for (const [id, history] of histories) { + const eligible = history.every((unknown) => { + if (unknown.scope_digest !== sha256) return false; + const mutationEvidenceIds = new Set(unknown.mutation_evidence_ids); + return referencedEvidenceIds(unknown).every((evidenceId) => { + const record = recordsById.get(evidenceId); + // Mutation subjects record the target active at the time of an edit, + // which need not be the question's immutable investigation scope. + return ( + record?.subject?.digest.sha256 === sha256 || + (mutationEvidenceIds.has(evidenceId) && + record?.predicate_type === "rea.residual-unknown-mutation") + ); + }); }); - if (!evidenceAvailable) continue; - retained.add(unknown); - revisionsById.set( - unknown.unknown_id, - (revisionsById.get(unknown.unknown_id) ?? 0) + 1, + if (!eligible) continue; + retained.add(id); + const relatedIds = new Set( + history.flatMap((unknown) => + unknown.relationships.map(({ unknown_id }) => unknown_id), + ), ); - for (const relatedId of new Set( - unknown.relationships.map(({ unknown_id: id }) => id), - )) { - const references = - dependents.get(relatedId) ?? new Set(); - references.add(unknown); + relationships.set(id, relatedIds); + for (const relatedId of relatedIds) { + const references = dependents.get(relatedId) ?? new Set(); + references.add(id); dependents.set(relatedId, references); } } - const pending: ResidualUnknown[] = []; - for (const unknown of retained) - if ( - unknown.relationships.some(({ unknown_id: id }) => !revisionsById.has(id)) - ) - pending.push(unknown); + const pending: string[] = []; + for (const [id, relatedIds] of relationships) + if ([...relatedIds].some((relatedId) => !retained.has(relatedId))) + pending.push(id); for (let index = 0; index < pending.length; index += 1) { - const unknown = pending[index]; - if (unknown === undefined || !retained.delete(unknown)) continue; - const remaining = (revisionsById.get(unknown.unknown_id) ?? 1) - 1; - if (remaining > 0) { - revisionsById.set(unknown.unknown_id, remaining); - continue; - } - revisionsById.delete(unknown.unknown_id); - for (const dependent of dependents.get(unknown.unknown_id) ?? []) - pending.push(dependent); + const id = pending[index]; + if (id === undefined || !retained.delete(id)) continue; + for (const dependent of dependents.get(id) ?? []) pending.push(dependent); } - const unknowns = candidates.filter((unknown) => retained.has(unknown)); + const unknowns = bundle.unknowns.filter((unknown) => + retained.has(unknown.unknown_id), + ); const mutationIds = new Set( unknowns.flatMap(({ mutation_evidence_ids: ids }) => ids), ); diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts index 832b55e40..b1a7bcf50 100644 --- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts +++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts @@ -24,6 +24,7 @@ import { ok } from "../../../src/domain/result.js"; import { silentLogger } from "../../../src/logger.js"; import { createServer } from "../../../src/server/createServer.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { recordUnknownInputSchema } from "../../../src/domain/residualUnknown.js"; const identity = { id: "fixture", name: "Fixture", version: "1" } as const; const profile = createAnalysisProfile(identity, { fixture: true }); @@ -217,6 +218,146 @@ describe("MCP composed workflow snapshot replay", () => { }); }); +describe("MCP investigation history snapshot replay", () => { + it.each(["verified", "withdrawn", "out-of-scope"] as const)( + "preserves a target's %s resolution recorded while another target is active", + async (disposition) => { + const { targetPaths, snapshotPath } = await createWorkflowFiles( + "rea-mcp-investigation-history-", + ["first.hop", "second.hop"], + ); + const firstPath = targetPaths[0]; + const secondPath = targetPaths[1]; + if (firstPath === undefined || secondPath === undefined) + throw new Error("Expected two investigation targets"); + const session = createWorkflowSession(makeProvider([], [])); + const { mcp } = await connectWorkflowMcp( + session, + "investigation-history", + ); + await openWorkflowTarget(mcp, firstPath); + const input = recordUnknownInputSchema.parse({ + question: "Has the string inventory been inspected for this target?", + severity: "medium", + domain: "investigation-history", + required_authority: null, + required_confidence: "derived", + required_environment: null, + recommended_probes: [], + relationships: [], + }); + const recorded = await mcp.callTool({ + name: "record_unknown", + arguments: input, + }); + expect(recorded.isError).not.toBe(true); + const unknown = toolContract("record_unknown").outputSchema.parse( + recorded.structuredContent, + ).result; + const resolutionEvidenceIds: string[] = []; + if (disposition === "verified") { + const inspected = await mcp.callTool({ + name: "list_strings", + arguments: {}, + }); + expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe( + true, + ); + resolutionEvidenceIds.push( + z + .string() + .parse( + toolContract("list_strings").outputSchema.parse( + inspected.structuredContent, + ).evidence_id, + ), + ); + } + await openWorkflowTarget(mcp, secondPath); + const unrelated = await mcp.callTool({ + name: "list_strings", + arguments: {}, + }); + expect(unrelated.isError).not.toBe(true); + const foreignEvidence = toolContract("list_strings").outputSchema.parse( + unrelated.structuredContent, + ); + const updated = await mcp.callTool({ + name: "update_unknown", + arguments: { + unknown_id: unknown.unknown_id, + expected_revision: unknown.revision, + status: "resolved", + severity: input.severity, + supporting_evidence_ids: resolutionEvidenceIds, + contradicting_evidence_ids: input.contradicting_evidence_ids, + required_authority: input.required_authority, + required_confidence: input.required_confidence, + required_environment: input.required_environment, + recommended_probes: input.recommended_probes, + relationships: input.relationships, + resolution: { + disposition, + rationale: "Disposition recorded after further investigation.", + evidence_ids: resolutionEvidenceIds, + }, + }, + }); + expect(updated.isError, JSON.stringify(updated.content)).not.toBe(true); + const resolved = toolContract("update_unknown").outputSchema.parse( + updated.structuredContent, + ).result; + expect(resolved).toMatchObject({ + revision: 2, + status: "resolved", + scope_digest: unknown.scope_digest, + }); + await openWorkflowTarget(mcp, firstPath); + const closed = await mcp.callTool({ + name: "close_binary", + arguments: { snapshot_path: snapshotPath }, + }); + expect(closed.isError, JSON.stringify(closed.content)).not.toBe(true); + const snapshot = await readAnalysisSnapshot(snapshotPath); + if (!snapshot.ok) throw snapshot.error; + expect(snapshot.value.evidence_bundle.unknowns).toEqual([ + unknown, + resolved, + ]); + expect(snapshot.value.evidence_bundle.records).toContainEqual( + expect.objectContaining({ + operation: "update_unknown", + subject: expect.objectContaining({ local_path: secondPath }), + }), + ); + expect(snapshot.value.evidence_bundle.records).not.toContainEqual( + foreignEvidence, + ); + + const replay = createWorkflowSession(makeProvider([], [])); + const { mcp: replayMcp } = await connectWorkflowMcp( + replay, + "investigation-history-replay", + ); + const reopened = await replayMcp.callTool({ + name: "open_binary", + arguments: { path: firstPath, snapshot_path: snapshotPath }, + }); + expect(reopened.isError, JSON.stringify(reopened.content)).not.toBe(true); + const listed = await replayMcp.callTool({ + name: "list_unknowns", + arguments: {}, + }); + expect(listed.isError).not.toBe(true); + expect( + toolContract("list_unknowns").outputSchema.parse( + listed.structuredContent, + ).result, + ).toEqual({ items: [resolved], total: 1 }); + }, + ); +}); + const createWorkflowFiles = async ( prefix: string, filenames: readonly string[], @@ -322,7 +463,7 @@ const makeProvider = ( ? ["fixture"] : operation === "list_procedures" ? ["0x1000"] - : { "0x1000": "fixture" }; + : [{ address: "0x1000", value: "fixture" }]; return ok(createAnalysisExecution(result, identity)); }, close: () => Promise.resolve(ok(null)), From a9f5dad5a8f196c88f6305d8d958b355cc0b52c2 Mon Sep 17 00:00:00 2001 From: You Wish <29498139+Y0UW1SH@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:39:56 -0400 Subject: [PATCH 118/189] fix(javascript): resolve exported callables through lexical bindings (#1351) * fix(javascript): resolve exported callables through lexical bindings * fix(javascript): preserve export scope and hoisted writes * test(javascript): consolidate export binding assertions * fix(javascript): account for skipped initializers and loop binding writes * fix(javascript): preserve parameters copied into body variables --- .../javascript/javascriptSemanticAnalysis.ts | 170 ++++- .../javascriptSemanticMemberMutations.ts | 6 +- .../javascriptSemanticProjection.ts | 188 +++--- .../javascript/javascriptSemanticReturns.ts | 37 +- .../javascript/javascriptSemanticState.ts | 6 + .../exportedFunctionBindingsCli.test.ts | 618 ++++++++++++++++++ 6 files changed, 929 insertions(+), 96 deletions(-) create mode 100644 tests/acceptance/applications/exportedFunctionBindingsCli.test.ts diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index f922fa6e6..7bdbdcc09 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -286,6 +286,8 @@ const createState = (program: t.Program): JavaScriptSemanticAnalysisState => { callables: [], callableNodesById: new Map(), moduleLinks: [], + moduleLinkBindings: new WeakMap(), + conditionalInitializers: new WeakSet(), }; }; @@ -297,9 +299,34 @@ const collectDefinitions = ( currentSemanticScope(state.scopes), ]; const openedScopes = new WeakMap(); + const assignments: { + readonly node: t.Node; + readonly scope: JavaScriptSemanticScopeState; + }[] = []; + const functionBodies: { + readonly body: t.BlockStatement; + readonly scope: JavaScriptSemanticScopeState; + readonly parameters: t.Function["params"]; + }[] = []; traverseJavaScriptAst(program, { - enter: (node, parent) => { + enter: (node, parent, readAncestors) => { let parentScope = currentSemanticScope(stack); + if ( + parent !== null && + (t.isObjectMethod(parent) || t.isClassMethod(parent)) && + parent.computed && + parent.key === node && + parentScope.parentScopeId !== null + ) { + // A computed method key is evaluated before entering the method's + // parameter and body environments. + const keyScope = state.scopesById.get(parentScope.parentScopeId); + if (keyScope !== undefined) { + stack.push(keyScope); + openedScopes.set(node, 1); + parentScope = keyScope; + } + } if ( parent !== null && t.isWithStatement(parent) && @@ -324,6 +351,12 @@ const collectDefinitions = ( if (nested !== undefined) { stack.push(nested); openedScopes.set(node, (openedScopes.get(node) ?? 0) + 1); + if (t.isBlockStatement(node) && t.isFunction(parent)) + functionBodies.push({ + body: node, + scope: nested, + parameters: parent.params, + }); } const scope = currentSemanticScope(stack); state.scopeByNode.set(node, scope); @@ -335,12 +368,95 @@ const collectDefinitions = ( state, }); bindInnerDeclaration(node, parent, scope, state); + if ( + t.isVariableDeclarator(node) && + node.init != null && + parent !== null && + t.isVariableDeclaration(parent, { kind: "var" }) && + hasConditionalInitializer(readAncestors()) + ) + state.conditionalInitializers.add(node.init); + if ( + t.isAssignmentExpression(node) || + t.isUpdateExpression(node) || + t.isForOfStatement(node) || + t.isForInStatement(node) + ) + assignments.push({ node, scope }); }, exit: (node) => { for (let count = openedScopes.get(node) ?? 0; count > 0; count--) stack.pop(); }, }); + // All declarations must exist before resolving writes, including hoisted + // functions and local declarations that shadow an outer binding. + for (const { node, scope } of assignments) bindAssignment(node, scope, state); + for (const { body, scope, parameters } of functionBodies) + for (const parameter of parameters) + for (const identifier of assignedPatternIdentifiers( + t.isTSParameterProperty(parameter) ? parameter.parameter : parameter, + )) + copyParameterToBody({ identifier, body, scope, state }); +}; + +const copyParameterToBody = (input: { + readonly identifier: t.Identifier; + readonly body: t.BlockStatement; + readonly scope: JavaScriptSemanticScopeState; + readonly state: JavaScriptSemanticAnalysisState; +}): void => { + const { identifier, body, scope, state } = input; + const binding = scope.bindings.get(identifier.name); + if ( + binding === undefined || + binding.kind !== "variable" || + binding.definitions.some(({ kind }) => kind === "function") + ) + return; + // A separate body var environment starts with the parameter's value. The + // real parameter identifier retains its scope and source location; entryBody + // records when the copy occurs without inventing an expression in the AST. + binding.initializers.unshift({ + node: identifier, + projection: [], + entryBody: body, + }); + for (let index = binding.initializers.length - 1; index >= 0; index -= 1) { + const initializer = binding.initializers[index]; + if ( + initializer !== undefined && + initializer.entryBody === undefined && + initializer.projection.length === 0 && + t.isIdentifier(initializer.node) && + resolveSemanticBindingState( + state, + initializer.node, + initializer.node.name, + ) === binding + ) + // Direct self-initialization preserves the prior value, including any + // actual overwrite before it. Keep the source definition/reference facts. + binding.initializers.splice(index, 1); + } +}; + +const hasConditionalInitializer = (ancestors: readonly t.Node[]): boolean => { + // A hoisted var can remain undefined when control flow skips its initializer. + // Conditions outside the owning callable/static block do not govern its body. + for (let index = ancestors.length - 1; index >= 0; index -= 1) { + const node = ancestors[index]; + if (t.isFunction(node) || t.isProgram(node) || t.isStaticBlock(node)) + return false; + if ( + t.isIfStatement(node) || + t.isLoop(node) || + t.isSwitchCase(node) || + t.isTryStatement(node) + ) + return true; + } + return false; }; const bindOuterDeclaration = ( @@ -408,7 +524,14 @@ const bindInnerDeclaration = ( mutable: true, kind: "catch", }); - else if (t.isAssignmentExpression(node)) { +}; + +const bindAssignment = ( + node: t.Node, + scope: JavaScriptSemanticScopeState, + state: JavaScriptSemanticAnalysisState, +): void => { + if (t.isAssignmentExpression(node)) { if (t.isIdentifier(node.left)) addAssignment( node.left, @@ -426,8 +549,11 @@ const bindInnerDeclaration = ( } else if (t.isUpdateExpression(node) && t.isIdentifier(node.argument)) addAssignment(node.argument, node, scope, state); else if (t.isForOfStatement(node) || t.isForInStatement(node)) - for (const identifier of assignedPatternIdentifiers(node.left)) - addAssignment(identifier, node, scope, state); + for (const pattern of t.isVariableDeclaration(node.left) + ? node.left.declarations.map(({ id }) => id) + : [node.left]) + for (const identifier of assignedPatternIdentifiers(pattern)) + addAssignment(identifier, node, scope, state); }; const assignedPatternIdentifiers = ( @@ -539,12 +665,42 @@ const scopeKind = ( if (t.isStaticBlock(node)) return "static-block"; if ( t.isBlockStatement(node) && - !(parent !== null && t.isFunction(parent) && parent.body === node) - ) - return "block"; + parent !== null && + t.isFunction(parent) && + parent.body === node + ) { + // Parameter expressions cannot see declarations in the function body. + // Retain the outer function scope for parameters and callable ownership; + // body declarations belong to a separate variable environment. + return functionParametersHaveExpressions(parent) ? "function" : undefined; + } + if (t.isBlockStatement(node)) return "block"; return undefined; }; +const functionParametersHaveExpressions = (node: t.Function): boolean => { + const pending: t.Node[] = [...node.params]; + while (pending.length > 0) { + const parameter = pending.pop(); + if (t.isAssignmentPattern(parameter)) return true; + if (t.isTSParameterProperty(parameter)) pending.push(parameter.parameter); + else if (t.isRestElement(parameter)) pending.push(parameter.argument); + else if (t.isArrayPattern(parameter)) { + for (const element of parameter.elements) + if (element !== null) pending.push(element); + } else if (t.isObjectPattern(parameter)) { + for (const property of parameter.properties) { + if (t.isRestElement(property)) pending.push(property.argument); + else { + if (property.computed) return true; + pending.push(property.value); + } + } + } + } + return false; +}; + const bindImports = ( node: t.ImportDeclaration, scope: JavaScriptSemanticScopeState, diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 0d3a00f22..c9fa49558 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -171,8 +171,10 @@ const mutationInitializers = ( if (binding.initializers.length < 2) return binding.initializers; const mutationPosition = directMutationPosition(mutation, parents); if (mutationPosition === null) return binding.initializers; - const positions = binding.initializers.map(({ node }) => - directInitializerPosition(node, parents), + const positions = binding.initializers.map(({ node, entryBody }) => + entryBody === undefined + ? directInitializerPosition(node, parents) + : { body: entryBody.body, index: -1 }, ); if ( positions.some( diff --git a/src/domain/javascript/javascriptSemanticProjection.ts b/src/domain/javascript/javascriptSemanticProjection.ts index 53881d632..89b1e9ed6 100644 --- a/src/domain/javascript/javascriptSemanticProjection.ts +++ b/src/domain/javascript/javascriptSemanticProjection.ts @@ -20,7 +20,7 @@ import { evaluateSemanticBinding, evaluateSemanticProvenance, } from "./javascriptSemanticValues.js"; -import { range, stringValue } from "./javascriptStaticAnalysisHelpers.js"; +import { range } from "./javascriptStaticAnalysisHelpers.js"; import { propertyName, semanticStaticPropertyKey, @@ -68,25 +68,33 @@ export const collectSemanticModuleLink = ( ): void => { if (t.isImportDeclaration(node)) collectImports(node, state); else if (t.isExportAllDeclaration(node)) - addModuleLink(state, { - kind: "re-export", - specifier: node.source.value, - importedName: "*", - localName: null, - exportedName: "*", - location: range(node), - }); + addModuleLink( + state, + { + kind: "re-export", + specifier: node.source.value, + importedName: "*", + localName: null, + exportedName: "*", + location: range(node), + }, + node, + ); else if (t.isExportNamedDeclaration(node)) collectNamedExports(node, state); else if (t.isExportDefaultDeclaration(node)) - addModuleLink(state, { - kind: "export", - specifier: null, - importedName: null, - localName: defaultDeclarationName(node.declaration), - exportedName: "default", - callableId: semanticCallableIdForNode(node.declaration), - location: range(node), - }); + addModuleLink( + state, + { + kind: "export", + specifier: null, + importedName: null, + localName: defaultDeclarationName(node.declaration), + exportedName: "default", + callableId: semanticCallableIdForNode(node.declaration), + location: range(node), + }, + node, + ); else if (t.isVariableDeclarator(node)) collectRequireLink(node, state); else if (t.isAssignmentExpression(node)) collectCommonJsExport(node, state); }; @@ -233,27 +241,35 @@ const collectImports = ( state: JavaScriptSemanticAnalysisState, ): void => { if (node.specifiers.length === 0) - addModuleLink(state, { - kind: "import", - specifier: node.source.value, - importedName: null, - localName: null, - exportedName: null, - location: range(node), - }); + addModuleLink( + state, + { + kind: "import", + specifier: node.source.value, + importedName: null, + localName: null, + exportedName: null, + location: range(node), + }, + node, + ); for (const specifier of node.specifiers) - addModuleLink(state, { - kind: "import", - specifier: node.source.value, - importedName: t.isImportDefaultSpecifier(specifier) - ? "default" - : t.isImportNamespaceSpecifier(specifier) - ? "*" - : propertyName(specifier.imported), - localName: specifier.local.name, - exportedName: null, - location: range(specifier), - }); + addModuleLink( + state, + { + kind: "import", + specifier: node.source.value, + importedName: t.isImportDefaultSpecifier(specifier) + ? "default" + : t.isImportNamespaceSpecifier(specifier) + ? "*" + : propertyName(specifier.imported), + localName: specifier.local.name, + exportedName: null, + location: range(specifier), + }, + node, + ); }; const collectNamedExports = ( @@ -262,25 +278,33 @@ const collectNamedExports = ( ): void => { if (node.declaration !== null && node.declaration !== undefined) for (const localName of declarationNames(node.declaration)) - addModuleLink(state, { - kind: "export", - specifier: null, - importedName: null, - localName, - exportedName: localName, - callableId: declarationCallableId(node.declaration, localName), - location: range(node.declaration), - }); + addModuleLink( + state, + { + kind: "export", + specifier: null, + importedName: null, + localName, + exportedName: localName, + callableId: declarationCallableId(node.declaration, localName), + location: range(node.declaration), + }, + node, + ); for (const specifier of node.specifiers) if (t.isExportSpecifier(specifier)) - addModuleLink(state, { - kind: node.source == null ? "export" : "re-export", - specifier: node.source?.value ?? null, - importedName: propertyName(specifier.local), - localName: node.source == null ? propertyName(specifier.local) : null, - exportedName: propertyName(specifier.exported), - location: range(specifier), - }); + addModuleLink( + state, + { + kind: node.source == null ? "export" : "re-export", + specifier: node.source?.value ?? null, + importedName: propertyName(specifier.local), + localName: node.source == null ? propertyName(specifier.local) : null, + exportedName: propertyName(specifier.exported), + location: range(specifier), + }, + node, + ); }; const collectRequireLink = ( @@ -290,14 +314,18 @@ const collectRequireLink = ( const origin = semanticRequireOrigin(node.init, state); if (origin === undefined) return; for (const binding of requirePatternBindings(node.id, origin.importedPath)) - addModuleLink(state, { - kind: "require", - specifier: origin.specifier, - importedName: binding.importedName, - localName: binding.localName, - exportedName: null, - location: range(node), - }); + addModuleLink( + state, + { + kind: "require", + specifier: origin.specifier, + importedName: binding.importedName, + localName: binding.localName, + exportedName: null, + location: range(node), + }, + node, + ); }; const requirePatternBindings = ( @@ -334,15 +362,19 @@ const collectCommonJsExport = ( const exportedName = commonJsExportName(node.left, state); if (exportedName === undefined) return; const origin = semanticRequireOrigin(node.right, state); - addModuleLink(state, { - kind: "commonjs-export", - specifier: origin?.specifier ?? null, - importedName: origin?.importedPath.at(-1) ?? null, - localName: t.isIdentifier(node.right) ? node.right.name : null, - exportedName, - callableId: semanticCallableIdForNode(node.right), - location: range(node), - }); + addModuleLink( + state, + { + kind: "commonjs-export", + specifier: origin?.specifier ?? null, + importedName: origin?.importedPath.at(-1) ?? null, + localName: t.isIdentifier(node.right) ? node.right.name : null, + exportedName, + callableId: semanticCallableIdForNode(node.right), + location: range(node), + }, + node, + ); }; const addModuleLink = ( @@ -350,8 +382,18 @@ const addModuleLink = ( link: Omit & { readonly callableId?: string | null; }, + referenceNode: t.Node, ): void => { - state.moduleLinks.push({ ...link, callableId: link.callableId ?? null }); + const collected = { ...link, callableId: link.callableId ?? null }; + state.moduleLinks.push(collected); + if (link.localName !== null) { + const binding = resolveSemanticBindingState( + state, + referenceNode, + link.localName, + ); + if (binding !== undefined) state.moduleLinkBindings.set(collected, binding); + } }; /** Deterministic callable identity shared by collection and return recovery. */ diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts index 15b698a02..bb931fba5 100644 --- a/src/domain/javascript/javascriptSemanticReturns.ts +++ b/src/domain/javascript/javascriptSemanticReturns.ts @@ -93,19 +93,14 @@ export const resolveSemanticModuleCallables = ( callables: readonly JavaScriptSemanticCallable[], ): JavaScriptSemanticModuleLink[] => { const callableIds = new Set(callables.map(({ callableId }) => callableId)); - const root = state.scopes.find(({ kind }) => kind === "program"); return state.moduleLinks.map((link) => { - if (link.callableId !== null && callableIds.has(link.callableId)) - return link; - if (link.localName === null || root === undefined) - return { ...link, callableId: null }; - const named = callables.filter( - ({ name, containerScopeId }) => - name === link.localName && containerScopeId === root.scopeId, - ); - if (named.length === 1) - return { ...link, callableId: named[0]?.callableId ?? null }; - const binding = root.bindings.get(link.localName); + // Named exports follow their lexical binding, including every assignment. + // A declaration's ID or a callable's display name cannot prove that link. + if (link.localName === null) + return link.callableId !== null && callableIds.has(link.callableId) + ? link + : { ...link, callableId: null }; + const binding = state.moduleLinkBindings.get(link); const resolved = binding === undefined ? [] @@ -154,10 +149,24 @@ const callableIdsForBinding = ( admitted: ReadonlySet, seen: ReadonlySet, ): string[] => { - if (seen.has(binding.bindingId) || binding.initializers.length !== 1) + // A single initializer does not prove an assignment executes or replace + // the unknown incoming value of a parameter/catch binding. + if ( + seen.has(binding.bindingId) || + binding.initializers.length !== 1 || + binding.definitions.some( + ({ kind }) => + kind === "assignment" || kind === "parameter" || kind === "catch", + ) + ) return []; const initializer = binding.initializers[0]; - if (initializer === undefined || initializer.projection.length > 0) return []; + if ( + initializer === undefined || + initializer.projection.length > 0 || + state.conditionalInitializers.has(initializer.node) + ) + return []; return callableIdsForNode( initializer.node, state, diff --git a/src/domain/javascript/javascriptSemanticState.ts b/src/domain/javascript/javascriptSemanticState.ts index 7f17308b2..cd5f40e4b 100644 --- a/src/domain/javascript/javascriptSemanticState.ts +++ b/src/domain/javascript/javascriptSemanticState.ts @@ -12,6 +12,7 @@ import type { interface JavaScriptSemanticInitializer { readonly node: t.Node; readonly projection: readonly (string | number | null)[]; + readonly entryBody?: t.BlockStatement; } /** Mutable binding state used only while constructing the immutable IR. */ @@ -46,6 +47,11 @@ export interface JavaScriptSemanticAnalysisState { readonly callables: JavaScriptSemanticCallable[]; readonly callableNodesById: Map; readonly moduleLinks: JavaScriptSemanticModuleLink[]; + readonly moduleLinkBindings: WeakMap< + JavaScriptSemanticModuleLink, + JavaScriptSemanticBindingState + >; + readonly conditionalInitializers: WeakSet; } /** Return the active scope from a non-empty construction stack. */ diff --git a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts new file mode 100644 index 000000000..f32f9e5e2 --- /dev/null +++ b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts @@ -0,0 +1,618 @@ +import { execFile } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { promisify } from "node:util"; + +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { describe, expect, it } from "vitest"; +import { z } from "zod"; + +import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; +import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const execute = promisify(execFile); +const comparisonEnvelope = z.object({ + normalized_result: javaScriptExportShapeComparisonResultSchema, +}); + +describe("exported function binding resolution through the CLI", () => { + it.each([ + { + name: "a function declaration exported by a specifier", + exportName: "default", + source: (count: number) => + `function current() { return { count: 0 }; } + current = () => ({ count: ${String(count)} }); + export { current as default };`, + }, + { + name: "a directly exported function declaration", + exportName: "current", + source: (count: number) => + `export function current() { return { count: 0 }; } + current = () => ({ count: ${String(count)} });`, + }, + { + name: "a named default function declaration", + exportName: "default", + source: (count: number) => + `export default function current() { return { count: 0 }; } + current = () => ({ count: ${String(count)} });`, + }, + { + name: "a directly exported arrow binding", + exportName: "current", + source: (count: number) => + `export let current = () => ({ count: 0 }); + current = () => ({ count: ${String(count)} });`, + }, + { + name: "an arrow binding exported by a specifier", + exportName: "default", + source: (count: number) => + `let current = () => ({ count: 0 }); + current = () => ({ count: ${String(count)} }); + export { current as default };`, + }, + { + name: "a reassigned alias", + exportName: "default", + source: (count: number) => + `const original = () => ({ count: 0 }); + let current = original; + current = () => ({ count: ${String(count)} }); + export { current as default };`, + }, + { + name: "a conditional function reassignment", + exportName: "current", + source: (count: number) => + `export function current() { return { count: 0 }; } + if (true) current = () => ({ count: ${String(count)} });`, + }, + ])( + "keeps $name uncertain after reassignment", + async ({ source, exportName }) => { + const fixture = await analyzeVersions(source, exportName); + await expectRuntimeExports(fixture, (count) => ({ count })); + const result = await compareThroughCli(fixture); + expectUncertainComparison(result); + for (const evidence of [fixture.input.left, fixture.input.right]) { + const { normalized_result: analysis } = z + .object({ + normalized_result: javascriptApplicationAnalysisResultSchema, + }) + .parse(evidence); + expect( + analysis.graph.nodes + .flatMap(({ observations }) => observations) + .filter( + ({ properties }) => + properties.semantic_role === "export-return-shapes" && + properties.exported_name === exportName, + ), + ).toEqual([]); + } + }, + ); + + it("does not associate a private function name with a numeric export in CLI or MCP", async () => { + const fixture = await analyzeVersions( + (count) => + `const hidden = function current() { return { count: 0 }; }; + const current = ${String(count)}; + export { current as default };`, + "default", + ); + await expectRuntimeExports(fixture, (count) => count); + const cli = await compareThroughCli(fixture); + expectUncertainComparison(cli); + expect(await compareThroughMcp(fixture.input)).toEqual(cli); + }); +}); + +describe("stable exported function bindings through the CLI", () => { + it.each([ + { + name: "an anonymous default", + source: (count: number) => + `export default () => ({ kind: "result", count: ${String(count)} });`, + }, + { + name: "a named default declaration", + source: (count: number) => + `export default function current() { return { kind: "result", count: ${String(count)} }; }`, + }, + { + name: "a private named default expression", + source: (count: number) => + `export default (function current() { return { kind: "result", count: ${String(count)} }; });`, + }, + { + name: "a declaration alias", + source: (count: number) => + `function original() { return { kind: "result", count: ${String(count)} }; } + const current = original; export { current as default };`, + }, + { + name: "an unchanged mutable binding", + source: (count: number) => + `let current = () => ({ kind: "result", count: ${String(count)} }); export { current as default };`, + }, + { + name: "a private function reached through its real binding", + source: (count: number) => + `const current = function privateName() { return { kind: "result", count: ${String(count)} }; }; + const privateName = 99; const alias = current; export { alias as default };`, + }, + { + name: "a declaration sharing a private display name", + source: (count: number) => + `const hidden = function current() { return { count: 99 }; }; + function current() { return { kind: "result", count: ${String(count)} }; } + export { current as default };`, + }, + ])("retains exact comparison for $name", async ({ source }) => { + const fixture = await analyzeVersions(source, "default"); + expectCountChange(await compareThroughCli(fixture)); + }); +}); + +describe("export bindings with loop and assignment-only writes", () => { + it.each([ + ["a skipped branch", "if (false)"], + ["a zero-iteration loop", "for (; false;)"], + ["an unselected switch case", "switch (0) { case 1:"], + ["an interrupted try block", "try { throw 1;"], + ])("does not infer a callable initialized in %s", async (_, prefix) => { + const fixture = await analyzeVersions((count) => { + const initializer = `var current = () => ({ count: ${String(count)} });`; + const statement = prefix.startsWith("try") + ? `${prefix} ${initializer} } catch {}` + : prefix.startsWith("switch") + ? `${prefix} ${initializer} }` + : `${prefix} { ${initializer} }`; + return `${statement} export { current as default };`; + }, "default"); + await expectRuntimeExports(fixture, () => undefined); + expectUncertainComparison(await compareThroughCli(fixture)); + }); + + it("retains a var initializer in an unconditional nested block", async () => { + const fixture = await analyzeVersions( + (count) => + `{ var current = () => ({ kind: "result", count: ${String(count)} }); } + export { current as default };`, + "default", + ); + await expectRuntimeExports(fixture, (count) => ({ kind: "result", count })); + expectCountChange(await compareThroughCli(fixture)); + }); + + it.each([ + { + name: "a for-of var declaration", + loop: (count: number) => + `for (var current of [() => ({ count: ${String(count)} })]) {}`, + }, + { + name: "a destructured for-of var declaration", + loop: (count: number) => + `for (var { value: current } of [{ value: () => ({ count: ${String(count)} }) }]) {}`, + }, + ])("keeps $name uncertain", async ({ loop }) => { + const fixture = await analyzeVersions( + (count) => + `function current() { return { count: 0 }; } + ${loop(count)} + module.exports = current;`, + "default", + "app.cjs", + ); + await expectRuntimeExports(fixture, (count) => ({ count })); + expectUncertainComparison(await compareThroughCli(fixture)); + }); + + it("does not associate a for-in key with the overwritten function", async () => { + const fixture = await analyzeVersions( + (count) => + `function current() { return { count: 0 }; } + for (var current in { ${String(count)}: true }) {} + module.exports = current;`, + "default", + "app.cjs", + ); + await expectRuntimeExports(fixture, String); + expectUncertainComparison(await compareThroughCli(fixture)); + }); + + it("preserves an outer export shadowed by a lexical loop declaration", async () => { + const fixture = await analyzeVersions( + (count) => + `export function current() { return { kind: "result", count: ${String(count)} }; } + for (let current of [() => ({ count: 0 })]) { current = null; }`, + "current", + ); + await expectRuntimeExports(fixture, (count) => ({ kind: "result", count })); + expectCountChange(await compareThroughCli(fixture)); + }); + + it.each([ + { + name: "a parameter", + source: (count: number) => + `function install(current) { + if (false) current = () => ({ count: 0 }); + module.exports = current; + } + install(${String(count)});`, + }, + { + name: "a catch binding", + source: (count: number) => + `try { throw ${String(count)}; } catch (current) { + if (false) current = () => ({ count: 0 }); + module.exports = current; + }`, + }, + { + name: "a parameter redeclared with var", + source: (count: number) => + `function install(current) { + if (false) { var current = () => ({ count: 0 }); } + module.exports = current; + } + install(${String(count)});`, + }, + ])("does not infer $name from its only assignment", async ({ source }) => { + const fixture = await analyzeVersions(source, "default", "app.cjs"); + await expectRuntimeExports(fixture, (count) => count); + const cli = await compareThroughCli(fixture); + expectUncertainComparison(cli); + expect(await compareThroughMcp(fixture.input)).toEqual(cli); + }); +}); + +describe("export binding lexical scope and declaration order", () => { + it.each([ + { + name: "a write before a hoisted function declaration", + source: (count: number) => + `current = () => ({ count: ${String(count)} }); + export function current() { return { count: 0 }; }`, + }, + { + name: "a nested write collected before its outer declaration", + source: (count: number) => + `function replace() { current = () => ({ count: ${String(count)} }); } + export function current() { return { count: 0 }; } + replace();`, + }, + ])("keeps $name uncertain", async ({ source }) => { + const fixture = await analyzeVersions(source, "current"); + await expectRuntimeExports(fixture, (count) => ({ count })); + expectUncertainComparison(await compareThroughCli(fixture)); + }); + + it("does not let a later local declaration contaminate the exported outer binding", async () => { + const fixture = await analyzeVersions( + (count) => + `export function current() { return { kind: "result", count: ${String(count)} }; } + function isolated() { + current = () => ({ count: 9 }); + function current() { return { count: 0 }; } + } + isolated();`, + "current", + ); + await expectRuntimeExports(fixture, (count) => ({ kind: "result", count })); + expectCountChange(await compareThroughCli(fixture)); + }); + + it("does not associate a nested CommonJS numeric export with an outer function", async () => { + const fixture = await analyzeVersions( + (count) => + `function current() { return { count: 0 }; } + function install() { const current = ${String(count)}; module.exports = current; } + install();`, + "default", + "app.cjs", + ); + await expectRuntimeExports(fixture, (count) => count); + const cli = await compareThroughCli(fixture); + expectUncertainComparison(cli); + expect(await compareThroughMcp(fixture.input)).toEqual(cli); + }); + + it.each([ + { + name: "a nested function-local alias", + source: (count: number) => + `function current() { return { kind: "result", count: 0 }; } + function install() { + const actual = () => ({ kind: "result", count: ${String(count)} }); + const current = actual; module.exports = current; + } + install();`, + }, + { + name: "a block-local function", + source: (count: number) => + `const current = 0; + { const current = () => ({ kind: "result", count: ${String(count)} }); + module.exports = current; }`, + }, + ])("compares $name through its real CommonJS binding", async ({ source }) => { + const fixture = await analyzeVersions(source, "default", "app.cjs"); + await expectRuntimeExports(fixture, (count) => ({ kind: "result", count })); + expectCountChange(await compareThroughCli(fixture)); + }); +}); + +describe("export writes in function evaluation contexts", () => { + it.each([ + { body: "var arg; arg.value = COUNT;", uncertain: true }, + { body: "var arg = arg; arg.value = COUNT;", uncertain: true }, + { body: "arg.value = COUNT; var arg;", uncertain: true }, + { body: "arg.value = COUNT; var arg = {};", uncertain: true }, + { body: "var arg = {}; arg.value = COUNT;", uncertain: false }, + { body: "var arg; arg = {}; arg.value = COUNT;", uncertain: false }, + { body: "function arg() {} arg.value = COUNT;", uncertain: false }, + ])("retains parameter-copy timing for $body", async ({ body, uncertain }) => { + const fixture = await analyzeVersions( + (count) => + `const source = { value: 0 }; + export function current(arg = null, set = (arg = source)) { + ${body.replace("COUNT", String(count))} + return { kind: "result", count: source.value }; + }`, + "current", + ); + await expectRuntimeExports(fixture, (count) => ({ + kind: "result", + count: uncertain ? count : 0, + })); + for (const evidence of [fixture.input.left, fixture.input.right]) { + const { normalized_result: analysis } = z + .object({ + normalized_result: javascriptApplicationAnalysisResultSchema, + }) + .parse(evidence); + const observations = analysis.graph.nodes.flatMap( + ({ observations }) => observations, + ); + expect(observations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + properties: expect.objectContaining({ + semantic_role: "export-return-shapes", + exported_name: "current", + static_return_shapes: [ + expect.objectContaining({ + fields: expect.arrayContaining([ + expect.objectContaining({ + path: "/count", + state: uncertain ? "unknown" : "literal", + value: uncertain ? null : 0, + }), + ]), + }), + ], + }), + }), + ]), + ); + } + }); + + it.each([ + ...["let current;", "var current;", "function current() {}"].map( + (body) => ({ + name: `a parameter default before ${body}`, + source: (count: number) => + `export function current() { return { count: 0 }; } + function replace(value = (current = () => ({ count: ${String(count)} }))) { + ${body} + } + replace();`, + }), + ), + { + name: "a closure invoked from a parameter default", + source: (count: number) => + `export function current() { return { count: 0 }; } + function replace(value = (() => { current = () => ({ count: ${String(count)} }); })()) { + let current; + } + replace();`, + }, + { + name: "a computed destructuring parameter key", + source: (count: number) => + `export function current() { return { count: 0 }; } + function replace({ [current = () => ({ count: ${String(count)} })]: value }) { + var current; + } + replace({});`, + }, + { + name: "an object method's computed key", + source: (count: number) => + `export function current() { return { count: 0 }; } + const object = { [current = () => ({ count: ${String(count)} })]() { let current; } };`, + }, + { + name: "a class method's computed key", + source: (count: number) => + `export function current() { return { count: 0 }; } + class Example { [current = () => ({ count: ${String(count)} })]() { var current; } }`, + }, + ])("keeps an outer export write in $name uncertain", async ({ source }) => { + const fixture = await analyzeVersions(source, "current"); + await expectRuntimeExports(fixture, (count) => ({ count })); + expectUncertainComparison(await compareThroughCli(fixture)); + }); + + it("resolves a CommonJS export in a parameter default outside the function body", async () => { + const fixture = await analyzeVersions( + (count) => + `function current() { return { kind: "result", count: ${String(count)} }; } + function install(value = (module.exports = current)) { var current = 9; } + install();`, + "default", + "app.cjs", + ); + await expectRuntimeExports(fixture, (count) => ({ kind: "result", count })); + expectCountChange(await compareThroughCli(fixture)); + }); +}); + +const expectRuntimeExports = async ( + fixture: Awaited>, + expected: (count: number) => unknown, +): Promise => { + // Execute only source-owned fixtures as an independent runtime oracle. + for (const [path, exportName, count] of [ + [fixture.leftPath, fixture.input.left_export_name, 1], + [fixture.rightPath, fixture.input.right_export_name, 2], + ] as const) + expect(await runtimeExport(path, exportName)).toEqual(expected(count)); +}; + +const expectUncertainComparison = ( + result: Awaited>, +): void => { + expect(result).toMatchObject({ + left: { status: "unavailable" }, + right: { status: "unavailable" }, + summary: { added: 0, removed: 0, changed: 0, unknown: 1 }, + changes: [{ status: "unknown", path: "" }], + coverage: { status: "partial" }, + }); + expect(result.property_inventories).toEqual([]); +}; + +const expectCountChange = ( + result: Awaited>, +): void => { + expect(result).toMatchObject({ + left: { status: "selected" }, + right: { status: "selected" }, + summary: { added: 0, removed: 0, changed: 1, unknown: 0 }, + changes: [ + { + path: "/count", + status: "changed", + left: { availability: "literal", value: 1 }, + right: { availability: "literal", value: 2 }, + }, + ], + coverage: { status: "complete-within-inputs" }, + }); +}; + +const runCli = async (args: readonly string[]): Promise => { + const { stdout } = await execute( + process.execPath, + [resolve("scripts/rea.mjs"), ...args], + { + maxBuffer: 16 * 1024 * 1024, + env: { ...process.env, REA_LOG_LEVEL: "silent" }, + }, + ); + return JSON.parse(stdout); +}; + +const analyzeVersions = async ( + source: (count: number) => string, + exportName: string, + fileName = "app.mjs", +) => { + const root = await createTestTempDirectory("rea-exported-function-bindings-"); + const leftRoot = join(root, "left"); + const rightRoot = join(root, "right"); + await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]); + const leftPath = join(leftRoot, fileName); + const rightPath = join(rightRoot, fileName); + await Promise.all([ + writeFile(leftPath, source(1)), + writeFile(rightPath, source(2)), + ]); + const [left, right] = await Promise.all([ + runCli(["analyze-javascript-application", leftRoot, "--json"]), + runCli(["analyze-javascript-application", rightRoot, "--json"]), + ]); + return { + root, + leftPath, + rightPath, + input: { + left, + right, + left_module_path: fileName, + left_export_name: exportName, + right_module_path: fileName, + right_export_name: exportName, + }, + }; +}; + +const compareThroughCli = async ( + fixture: Awaited>, +) => { + const inputPath = join(fixture.root, "comparison.json"); + await writeFile(inputPath, JSON.stringify(fixture.input)); + return comparisonEnvelope.parse( + await runCli(["compare-javascript-export-shapes", inputPath, "--json"]), + ).normalized_result; +}; + +const compareThroughMcp = async (input: Record) => { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + cwd: process.cwd(), + env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" }, + stderr: "pipe", + }); + const client = new Client({ + name: "exported-function-bindings", + version: "1", + }); + try { + await client.connect(transport); + const response = await client.callTool({ + name: "compare_javascript_export_shapes", + arguments: input, + }); + expect(response.isError).not.toBe(true); + return comparisonEnvelope.parse(response.structuredContent) + .normalized_result; + } finally { + try { + await client.close(); + } finally { + await transport.close(); + } + } +}; + +const runtimeExport = async ( + path: string, + exportName: string, +): Promise => { + const { stdout } = await execute(process.execPath, [ + "--input-type=module", + "-e", + `import { pathToFileURL } from 'node:url'; + const module = await import(pathToFileURL(process.argv[1]).href); + const value = module[process.argv[2]]; + console.log(JSON.stringify({ value: typeof value === 'function' ? value() : value }));`, + path, + exportName, + ]); + return z.object({ value: z.unknown().optional() }).parse(JSON.parse(stdout)) + .value; +}; From d0e606930acb701790c286340226b1e3e7060b4f Mon Sep 17 00:00:00 2001 From: Akshit Khokhani <67451993+akshitkhokhani@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:49:43 -0500 Subject: [PATCH 119/189] fix(javascript): honor module-sync package exports (#1361) --- docs/javascript-artifact-reconstruction.md | 2 ++ .../JavaScriptArtifactPathResolution.ts | 4 ++- .../javascriptPackageExportTargets.test.ts | 21 ++++++++++++ .../javascriptPackagePrecedence.test.ts | 33 ++++++++++++++++++- 4 files changed, 58 insertions(+), 2 deletions(-) diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md index 3a996e5f9..68c65ca75 100644 --- a/docs/javascript-artifact-reconstruction.md +++ b/docs/javascript-artifact-reconstruction.md @@ -307,6 +307,8 @@ such as `./web3:app.js` still names a local artifact. Package `exports` fallback arrays are supported both at the top level and under the root `"."` entry. The resolver selects targets in declared order using the same conditional and invalid-entry handling as nested exports arrays. +For imports and requires, the active Node conditions include `module-sync`; +earlier active conditions retain precedence over later ones. ESM relative module paths and selected package exports targets use URL suffix handling and one percent-decoding pass. CommonJS relative paths and legacy package main diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts index c28cd45c5..f87cc2455 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts @@ -640,7 +640,8 @@ const exportTargets = ( * Node selects an exports target by walking the declared keys in order and * taking the first whose condition is active for the calling resolver. * "default" is always active, and "node" plus "node-addons" are active for the - * built-in resolver that owns installed-package imports and requires. + * built-in resolver that owns installed-package imports and requires. The + * supported Node runtimes also activate "module-sync" for both loaders. */ const packageExportConditions = ( moduleKind: ResolveArtifactPathInput["moduleKind"], @@ -648,6 +649,7 @@ const packageExportConditions = ( new Set([ "node", "node-addons", + "module-sync", ...(moduleKind === undefined ? [] : [moduleKind]), "default", ]); diff --git a/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts b/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts index 4d22c8a7a..aa8596cb6 100644 --- a/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts +++ b/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts @@ -103,6 +103,27 @@ const cases: readonly { exports: { browser: "./../outside.cjs", default: "./actual.cjs" }, expected: "node_modules/fixture/actual.cjs", }, + { + name: "active module-sync rejects an invalid target instead of default", + exports: { "module-sync": "./../outside.cjs", default: "./actual.cjs" }, + expected: null, + nodeError: "ERR_INVALID_PACKAGE_TARGET", + rejectedTarget: "./../outside.cjs", + }, + { + name: "module-sync null blocks default", + exports: { "module-sync": null, default: "./actual.cjs" }, + expected: null, + nodeError: "ERR_PACKAGE_PATH_NOT_EXPORTED", + }, + { + name: "unmatched nested module-sync permits default", + exports: { + "module-sync": { browser: "./missing.cjs" }, + default: "./actual.cjs", + }, + expected: "node_modules/fixture/actual.cjs", + }, ...["./bad%.cjs", "./bad%C3.cjs"].map((target) => ({ name: `malformed URL ${target} is selected before URL decoding`, exports: [target, "./actual.cjs"], diff --git a/tests/boundary/filesystem/javascriptPackagePrecedence.test.ts b/tests/boundary/filesystem/javascriptPackagePrecedence.test.ts index 4c730fb73..8bc2511e1 100644 --- a/tests/boundary/filesystem/javascriptPackagePrecedence.test.ts +++ b/tests/boundary/filesystem/javascriptPackagePrecedence.test.ts @@ -202,6 +202,36 @@ it.each([ exports: { import: "./exported.mjs", require: "./actual.cjs" }, }, }, + { + name: "import selects module-sync before default", + kind: "import", + metadata: { + exports: { "module-sync": "./sync.mjs", default: "./actual.cjs" }, + }, + }, + { + name: "require selects nested module-sync before default", + kind: "require", + metadata: { + exports: { + ".": { node: { "module-sync": "./sync.mjs", default: "./actual.cjs" } }, + }, + }, + }, + { + name: "an earlier import condition precedes module-sync", + kind: "import", + metadata: { + exports: { import: "./exported.mjs", "module-sync": "./sync.mjs" }, + }, + }, + { + name: "an earlier default condition precedes module-sync", + kind: "require", + metadata: { + exports: { default: "./actual.cjs", "module-sync": "./sync.mjs" }, + }, + }, ] as const)( "matches the native Node loader when $name", async ({ kind, metadata }) => { @@ -210,7 +240,7 @@ it.each([ const source = kind === "import" ? `import value from "fixture"; console.log(JSON.stringify({value, resolved: import.meta.resolve("fixture")}));` - : `const value = require("fixture"); console.log(JSON.stringify({value, resolved: require.resolve("fixture")}));`; + : `const value = require("fixture"); console.log(JSON.stringify({value: typeof value === "string" ? value : value.default, resolved: require.resolve("fixture")}));`; const files = { "package.json": JSON.stringify({ name: "app", @@ -226,6 +256,7 @@ it.each([ "node_modules/fixture/index.js": "module.exports = 'index.js';", "node_modules/fixture/bundler.mjs": "export default 'bundler.mjs';", "node_modules/fixture/exported.mjs": "export default 'exported.mjs';", + "node_modules/fixture/sync.mjs": "export default 'sync.mjs';", }; await Promise.all( Object.entries(files).map(async ([path, text]) => { From 355a292198bf58245c67ae315fdb4f77e62769cc Mon Sep 17 00:00:00 2001 From: You Wish <29498139+Y0UW1SH@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:53:42 -0400 Subject: [PATCH 120/189] fix(javascript): preserve uncertainty after references escape to calls (#1292) * fix(javascript): preserve uncertainty after references escape to calls * fix(javascript): track iterator root escapes and preserve static captures * fix(javascript): scope comparison unknowns to their evidence * fix(javascript): track parameter origins at function body entry --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/javascript-application-workflows.md | 24 +- ...tSemanticAnalysis.member_mutations.test.ts | 371 +++++++++ ...manticAnalysis.reference_lifetimes.test.ts | 313 +++++++ .../javascript/javascriptSemanticAnalysis.ts | 92 ++- .../javascriptSemanticIterationSources.ts | 163 ++++ .../javascriptSemanticMemberMutations.ts | 780 ++++++++++++++---- ...scriptSemanticMutationInitializers.test.ts | 63 ++ .../javascriptSemanticMutationInitializers.ts | 228 +++++ .../javascriptSemanticMutationValues.ts | 96 ++- .../javascriptSemanticPropertyPaths.ts | 37 + .../javascript/javascriptSemanticState.ts | 20 +- .../javascript/javascriptSemanticValues.ts | 138 +++- .../compareExportShapes.ts | 4 +- .../registerApplicationTools/helpers.ts | 6 +- .../applicationWorkflowCli.test.ts | 246 ++++++ .../javascriptExportShapeComparison.test.ts | 58 ++ .../mcp/applicationExportShapeMcp.test.ts | 155 ++++ 17 files changed, 2574 insertions(+), 220 deletions(-) create mode 100644 src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts create mode 100644 src/domain/javascript/javascriptSemanticIterationSources.ts create mode 100644 src/domain/javascript/javascriptSemanticMutationInitializers.test.ts create mode 100644 src/domain/javascript/javascriptSemanticMutationInitializers.ts create mode 100644 src/domain/javascript/javascriptSemanticPropertyPaths.ts diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index e7ae76acb..cb3e1e5e9 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -69,13 +69,12 @@ validation boundaries, and built-in resource acquisition/release. Mutation tracking covers explicit member assignments, updates, deletion, and loop assignment targets, including the supported local aliases and shared -nested references. Calls such as `Object.assign`, `Reflect.set`, and -`Reflect.deleteProperty`, and writes reaching a caller's object through another -function's parameter, are not tracked by this mutation pass. These channels -can leave an initializer-derived literal in the graph even after the runtime -value changes. Treat such a result as an uncovered mutation channel, not as -proof of the current runtime value; a follow-up needs to model that channel -and verify its caller/alias behavior. +nested references. Calls conservatively invalidate exposed mutable references; +callee bodies and built-ins such as `Object.assign`, `Reflect.set`, and +`Reflect.deleteProperty` are not interpreted to establish exact post-call +values. This uncertainty does not prove that a call actually mutated a value. +Interprocedural aliasing beyond the supported call-site references remains +outside this mutation pass. Function fingerprints commit normalized syntax, control-flow shape, relation shape, literal sets, arity, and detected effects without using local names or @@ -146,6 +145,15 @@ Direct return expressions, including expression-bodied arrows, are evaluated through an execution-free value lattice. Literal object fields and direct return sites are represented in the result. Calls, dynamic spreads, computed keys, and parser recovery remain partial or unknown. +Objects and arrays passed to calls, constructors, or tagged templates, or used +as method receivers, are not assumed unchanged after the invocation. Aliases +and shared children in spread and rest copies retain that uncertainty; copied +primitive slots and unrelated containing properties remain known. Object rest +excludes consumed keys, array rest excludes the consumed prefix for known +arrays, and later explicit data properties and methods replace earlier object +spread references. A known array prefix does not expose values from a following +spread. Accessors, custom or uncertain iteration, unknown computed keys, and +unknown spread lengths retain conservative uncertainty. Nested callable returns are not assigned to their parent callable. Projected graph observations carry source ranges but never source text. @@ -171,6 +179,8 @@ value alone does not make an observed property uncertain. `summary.added` and `summary.removed` count presence-level add/remove as well as literal value add/remove; `summary.unknown` does not absorb complete-coverage presence-only gaps. +A partial comparison still records an unknown in the MCP session when matching +uncertain projections produce no changes and `summary.unknown` is zero. The output includes exact selector candidates, omissions, Evidence links, coverage, and limitations; it does not execute JavaScript. When runtime diff --git a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts index ac9d0de8a..f28436eb1 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts @@ -164,7 +164,378 @@ describe("JavaScript semantic values after explicit property mutations", () => { }); }); +describe("JavaScript semantic values after mutable references escape", () => { + it("preserves copied scalar slots while invalidating shared children of an escaped object spread", () => { + expect( + resultValue(` + const source = { kind: "record", child: { value: 1 } }; + const copy = { ...source }; + mutate(copy); + return source; + `), + ).toMatchObject({ + status: "object", + properties: [ + { name: "child", value: { status: "unknown" }, presence: "present" }, + { name: "kind", value: { status: "literal", value: "record" } }, + ], + }); + }); + + it("invalidates shared array children without invalidating copied primitives", () => { + expect( + resultValue(` + const child = { value: 1 }; + const source = [child, "TOKEN"]; + const copy = [...source]; + mutate(copy); + return { token: source[1], value: child.value }; + `), + ).toMatchObject({ + status: "object", + properties: [ + { name: "token", value: { status: "literal", value: "TOKEN" } }, + { name: "value", value: { status: "unknown" } }, + ], + }); + }); + + it("keeps primitive spread arguments known", () => { + expect( + resultValue( + 'const values = ["TOKEN"]; consume(...values); return values[0];', + ), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it("does not treat a member constructor as a call with its container as receiver", () => { + expect( + resultValue(` + const namespace = { token: "TOKEN", Factory: class {} }; + new namespace.Factory(); + return namespace.token; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it("does not reuse an initializer projection cached before call mutations were collected", () => { + expect( + resultValue(` + const source = { value: 1 }; + function observe() { consume(copy); } + mutate(source); + const copy = source.value; + return copy; + `)?.status, + ).toBe("unknown"); + }); + + it.each([ + "mutate(source as unknown);", + "mutate((0, source));", + "let alias; mutate(alias = source);", + "mutate(flag ? source : {});", + "let alias = source; mutate(alias ||= {});", + "let alias = source; mutate(alias ??= {});", + ])("follows a reference through %s", (invocation) => { + expect( + resultValue(` + const source = { value: 1 }; + ${invocation} + return source.value; + `)?.status, + ).toBe("unknown"); + }); +}); + +describe("JavaScript escaped references through async and destructuring syntax", () => { + it("follows an awaited object argument", () => { + const ir = analyzeJavaScriptSemantics(`export async function result() { + const source = { value: 1 }; + mutate(await source); + return source.value; + }`); + expect(onlyCallable(ir, "result").returnSites[0]?.value.status).toBe( + "unknown", + ); + }); + + it.each([ + "const { ...copy } = source; mutate(copy);", + "const { ...copy } = source; mutate(copy.child);", + "const [ ...copy ] = [source.child]; mutate(copy);", + "const [ first, ...copy ] = [null, source.child]; mutate(copy[0]);", + "const [ ...[copy] ] = [source.child]; mutate(copy);", + "const [ ...[copy = source.child] ] = []; mutate(copy);", + "const { value = source.child } = {}; mutate(value);", + "const [ value = source.child ] = []; mutate(value);", + ])("follows shared references through %s", (invocation) => { + expect( + resultValue(` + const source = { kind: "record", child: { value: 1 } }; + ${invocation} + return source; + `), + ).toMatchObject({ + status: "object", + properties: [ + { name: "child", value: { status: "unknown" }, presence: "present" }, + { name: "kind", value: { status: "literal", value: "record" } }, + ], + }); + }); + + it("keeps an unused default reference unchanged when destructuring a defined value", () => { + expect( + resultValue(` + const source = { value: "TOKEN" }; + const { value = source } = { value: 1 }; + mutate(value); + return source.value; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it("keeps an unused nested default reference unchanged", () => { + expect( + resultValue(` + const unused = { value: "TOKEN" }; + const { box: { value = unused } = { value: 1 } } = {}; + mutate(value); + return unused.value; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it("reconsiders a destructuring fallback after later collection finds an escape", () => { + expect( + resultValue(` + const fallback = { value: 1 }; + const source = { child: { value: 2 } }; + function observe() { mutate(copy); } + remove(source); + const { child: copy = fallback } = source; + mutate(copy); + return fallback.value; + `)?.status, + ).toBe("unknown"); + }); + + it("follows a fallback write when the original projection appeared primitive", () => { + expect( + resultValue(` + const fallback = { value: 1 }; + const source = { child: 1 }; + function observe() { copy.value = 2; } + remove(source); + const { child: copy = fallback } = source; + observe(); + return fallback.value; + `)?.status, + ).toBe("unknown"); + }); + + it("keeps fresh rest-copy slot writes from changing the original", () => { + expect( + resultValue(` + const source = { child: { value: "TOKEN" } }; + const { ...copy } = source; + copy.child = {}; + return source.child.value; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it("follows writes to shared children of rest copies", () => { + expect( + resultValue(` + const source = { kind: "record", child: { value: 1 } }; + const { ...copy } = source; + copy.child.value = 2; + return { kind: source.kind, value: source.child.value }; + `), + ).toMatchObject({ + status: "object", + properties: [ + { name: "kind", value: { status: "literal", value: "record" } }, + { name: "value", value: { status: "unknown" } }, + ], + }); + }); + + it.each([ + "const source = { skipped: {}, child: { value: 1 } }; const { skipped, ...copy } = source; mutate(copy); return source.child.value;", + "const source = [{}, { value: 1 }]; const [head, ...copy] = source; mutate(copy[0]); return source[1].value;", + "const source = [{}, { value: 1 }]; const [head, ...copy] = source; copy[0].value = 2; return source[1].value;", + "const source = { child: { value: 1 } }; const copy = { child: {}, ...source }; mutate(copy.child); return source.child.value;", + "const source = { child: { value: 1 } }; const copy = { ...source, [key]: {} }; mutate(copy.child); return source.child.value;", + "const source = [{ value: 1 }]; const copy = [{}, ...source]; mutate(copy[1]); return source[0].value;", + "const source = [{ value: 1 }]; const copy = [...other, ...source]; mutate(copy[0]); return source[0].value;", + "const source = [{ value: 1 }]; mutate([... [...source]]); return source[0].value;", + "const child = { value: 1 }; const source = { child, *[Symbol.iterator]() { yield this.child; } }; const copy = [{}, ...source]; mutate(copy[1]); return child.value;", + "const child = { value: 1 }; const source = { child, *[Symbol.iterator]() { yield null; yield this.child; } }; const [head, ...copy] = source; mutate(copy); return child.value;", + "const child = { value: 1 }; const source = [child]; source[Symbol.iterator] = function* () { yield null; yield this[0]; }; const [head, ...copy] = source; mutate(copy); return child.value;", + "const child = { value: 1 }; const source = [null, child]; source.__proto__ = { *[Symbol.iterator]() { yield this[1]; } }; const copy = [{}, ...source]; mutate(copy[1]); return child.value;", + "const source = [{ value: 1 }, {}]; Array.prototype[Symbol.iterator] = function* () { yield null; yield this[0]; }; const [head, ...copy] = source; mutate(copy[0]); return source[0].value;", + "const source = [null, { value: 1 }]; const prototype = Array.prototype; prototype[Symbol.iterator] = function* () { yield this[1]; }; const copy = [{}, ...source]; mutate(copy[1]); return source[1].value;", + "const source = [null, { value: 1 }]; const other = []; other.__proto__[Symbol.iterator] = function* () { yield this[1]; }; const copy = [{}, ...source]; mutate(copy[1]); return source[1].value;", + "const source = { child: { value: 1 } }; const copy = { ...source, get child() { return source.child; } }; mutate(copy.child); return source.child.value;", + "const source = { child: { value: 1 } }; const copy = { ...source, get child() { return source.child; }, set child(value) {} }; mutate(copy.child); return source.child.value;", + ])("preserves uncertainty for retained shared children: %s", (body) => { + expect(resultValue(body)?.status).toBe("unknown"); + }); + + it("finishes repeated alias branches without expanding identical escape paths", () => { + const declarations = Array.from({ length: 24 }, (_, index) => { + const name = `alias${String(index + 1)}`; + const previous = `alias${String(index)}`; + return `let ${name} = ${previous}; ${name} = ${previous};`; + }).join("\n"); + expect( + resultValue(` + let alias0 = { value: 1 }; + ${declarations} + mutate(alias24); + return alias0.value; + `)?.status, + ).toBe("unknown"); + }); +}); + +describe("JavaScript shared array iteration", () => { + it.each([ + "mutate(...source);", + "mutate?.(...source);", + "new Factory(...source);", + "const copy = [...source]; mutate(copy);", + "const copy = [{}, ...source]; mutate(copy[1]);", + "const copy = [...source]; copy[0].value = 2;", + "const [...copy] = source; mutate(copy);", + "const [...copy] = source; copy[0].value = 2;", + "const wrapper = { source }; const { source: [...copy] } = wrapper; mutate(copy);", + "const [copy] = source; mutate(copy);", + "let copy; [copy] = source; mutate(copy);", + "const { nested: [copy] } = { nested: source }; mutate(copy);", + "for (const copy of source) mutate(copy);", + "let copy; for (copy of source) mutate(copy);", + ])("invalidates an iterable that yields itself through %s", (effect) => { + expect( + resultValue(` + const source = { *[Symbol.iterator]() { yield this; }, value: "TOKEN" }; + ${effect} + return source.value; + `)?.status, + ).toBe("unknown"); + }); + + it.each([ + "const [copy] = source;", + "const copy = [...source];", + "for (const copy of source) {}", + "const { nested: [copy] } = { nested: source };", + "const [...[[copy]]] = [source];", + "const [...{ 0: [copy] }] = [source];", + "for (const [copy] of [source]) {}", + "const { missing: [copy] = source } = {};", + "function consume([copy] = source) {} consume();", + "function* copies() { yield* source; } consume(copies());", + ])("accounts for custom iterator receiver effects in %s", (iteration) => { + expect( + resultValue(` + const source = { *[Symbol.iterator]() { this.value = "changed"; yield this; }, value: "TOKEN" }; + ${iteration} + return source.value; + `)?.status, + ).toBe("unknown"); + }); + + it.each([ + "const [copy] = source;", + "const copy = [...source];", + "for (const copy of source) {}", + "const { nested: [copy] } = { nested: source };", + "const [...[[copy]]] = [source];", + "const [...{ 0: [copy] }] = [source];", + "for (const [copy] of [source]) {}", + ])("preserves ordinary array values after %s", (iteration) => { + expect( + resultValue(`const source = ["TOKEN"]; ${iteration} return source[0];`), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it.each([ + "const { nested: [copy] = source } = { nested: [] };", + "const [[copy] = source] = [[]];", + "const { a: { b: [copy] = source } = { b: [] } } = {};", + "for (const { nested: [copy] = source } of [{ nested: [] }]) {}", + "for (const [[copy] = source] of [[[]]]) {}", + "for (const { nested: [copy] = source } of []) {}", + ])("does not execute unused iterator defaults in %s", (iteration) => { + expect( + resultValue(` + const source = { *[Symbol.iterator]() { yield this; }, value: "TOKEN" }; + ${iteration} + return source.value; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); + + it.each([ + "source[Symbol.iterator] = function* () { yield this; };", + "Array.prototype[Symbol.iterator] = function* () { yield this; };", + ])("invalidates a custom array iterator's root after %s", (override) => { + expect( + resultValue(` + const source = ["TOKEN"]; + ${override} + mutate(...source); + return source[0]; + `)?.status, + ).toBe("unknown"); + }); + + it.each(["globalThis", "global", "window", "self"])( + "retains uncertainty after %s.Array.prototype changes", + (globalName) => { + expect( + resultValue(` + const source = [null, { value: 1 }]; + ${globalName}.Array.prototype[Symbol.iterator] = function* () { yield this[1]; }; + const copy = [{}, ...source]; + mutate(copy[1]); + return source[1].value; + `)?.status, + ).toBe("unknown"); + }, + ); + + it("respects a shadowed global object when checking iteration", () => { + expect( + resultValue(` + const globalThis = { Array: { prototype: {} } }; + globalThis.Array.prototype[Symbol.iterator] = function* () { yield null; }; + const source = [{ value: "TOKEN" }]; + const [head, ...copy] = source; + mutate(copy); + return source[0].value; + `), + ).toEqual({ status: "literal", value: "TOKEN" }); + }); +}); + const unchangedProperties = [ + 'const source = { only: { value: "TOKEN" } }; const { only, ...copy } = source; mutate(copy); return source.only.value;', + 'const source = [{ value: "TOKEN" }]; const [head, ...copy] = source; mutate(copy); return source[0].value;', + 'const source = { child: { value: "TOKEN" } }; const copy = { ...source, child: { value: 2 } }; mutate(copy.child); return source.child.value;', + 'const source = [{ value: "TOKEN" }]; const copy = [{ value: 0 }, ...source]; mutate(copy[0]); return source[0].value;', + 'const source = { child: { value: "TOKEN" } }; const copy = { ...source, ["child"]: { value: 2 } }; mutate(copy); return source.child.value;', + 'const child = { value: "TOKEN" }; const copy = { child, child: {} }; mutate(copy); return child.value;', + 'const source = [{ value: "TOKEN" }, { value: 2 }]; const [head, ...copy] = source; mutate(copy[0]); return source[0].value;', + 'const source = [{ value: "TOKEN" }, { value: 2 }]; const copy = [{}, ...source]; mutate(copy[2]); return source[0].value;', + 'const source = [{ value: "TOKEN" }]; const copy = [, ...source]; mutate(copy[0]); return source[0].value;', + 'const source = [{ value: "TOKEN" }]; const copy = [...source]; mutate(copy["01"]); return source[0].value;', + 'const source = { only: { value: "TOKEN" } }; const { ["only"]: consumed, ...copy } = source; mutate(copy); return source.only.value;', + 'const source = { child: { value: "TOKEN" } }; const copy = { ...source, child() {} }; mutate(copy); return source.child.value;', 'const source = { token: "TOKEN", count: 1 }; source.count = 2; return source.token;', 'const source = { token: "TOKEN", count: 1 }; const alias = source; alias.count++; return source.token;', 'const source = { token: "TOKEN", count: 1 }; delete source.count; return source.token;', diff --git a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts new file mode 100644 index 000000000..01a9566de --- /dev/null +++ b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts @@ -0,0 +1,313 @@ +import { describe, expect, it } from "vitest"; + +import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js"; +import { onlyCallable } from "./javascriptSemanticAnalysis.fixture.js"; + +const resultValue = (body: string) => + onlyCallable( + analyzeJavaScriptSemantics(`export function result() { ${body} }`), + "result", + ).returnSites[0]?.value; + +describe("reference lifetimes across calls and shallow copies", () => { + it("bounds dynamic destructuring across shared alias branches", () => { + const declarations = Array.from( + { length: 9 }, + (_, index) => + `const alias${index + 1} = { left: alias${index}, right: alias${index} };`, + ).join("\n"); + const pattern = "{ [key]: ".repeat(9) + "[copy]" + " }".repeat(9); + const start = performance.now(); + resultValue( + `const alias0 = [1]; ${declarations} const ${pattern} = alias9; return alias0[0];`, + ); + expect(performance.now() - start).toBeLessThan(2000); + }, 30000); + + it("bounds conditional shallow-copy traversal while retaining shared children", () => { + const declarations = Array.from( + { length: 20 }, + (_, i) => + `const alias${i + 1} = flag ? {...alias${i}, a${i}:{}} : {...alias${i}, b${i}:{}};`, + ).join("\n"); + const start = performance.now(); + expect( + resultValue( + `const alias0 = { value: { token: 1 } }; ${declarations} consume(alias20); return alias0.value.token;`, + )?.status, + ).toBe("unknown"); + expect(performance.now() - start).toBeLessThan(2000); + }, 30000); + + it.each([ + ["child: {}", "child: {}", "literal"], + ["child: {}", "other: {}", "unknown"], + ])( + "retains exclusions common to both branches: %s / %s", + (left, right, status) => { + expect( + resultValue( + `const source = {child:{value:1}}; const copy = flag ? {...source, ${left}} : {...source, ${right}}; consume(copy); return source.child.value;`, + )?.status, + ).toBe(status); + }, + ); + + it.each([ + "mutate(alias)", + "alias.method()", + "new Factory(alias)", + "tag`${alias}`", + "alias.tag``", + "mutate((0, alias))", + ])("drops replaced call origins for %s", (call) => { + expect( + resultValue( + `const source={value:1}; let alias=source; alias={}; ${call}; return source.value;`, + ), + ).toEqual({ status: "literal", value: 1 }); + }); + + it.each([ + "mutate(alias); alias={};", + "if(flag) alias={}; mutate(alias);", + "alias={}; if(flag) mutate(alias);", + "function invoke(){mutate(alias);} alias={}; invoke();", + "alias={}; mutate(alias); alias=source;", + ])("retains uncertain call ordering: %s", (body) => { + expect( + resultValue( + `const source={value:1}; let alias=source; ${body} return source.value;`, + )?.status, + ).toBe("unknown"); + }); + + it.each([ + ["let {...copy}={child};", "copy={child:{}};", "copy.child.value=2;"], + ["let [...copy]=[child];", "copy=[{}];", "copy[0].value=2;"], + ["let {copy=child}={};", "copy={};", "copy.value=2;"], + ["let [copy=child]=[];", "copy={};", "mutate(copy);"], + ])( + "drops replaced rest/default origins: %s", + (declaration, rebind, mutation) => { + expect( + resultValue( + `const child={value:1}; ${declaration} ${rebind} ${mutation} return child.value;`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const child={value:1}; ${declaration} if(flag) ${rebind} ${mutation} return child.value;`, + )?.status, + ).toBe("unknown"); + }, + ); +}); + +describe("primitive snapshots across calls", () => { + it.each([ + "const [copy] = source;", + "const copy = [...source];", + "for (const copy of source) {}", + ])("preserves snapshots taken before custom iteration: %s", (iteration) => { + expect( + resultValue(` + const source = { *[Symbol.iterator]() { yield this; }, value: 1 }; + const snapshot = source.value; + ${iteration} + return snapshot; + `), + ).toEqual({ status: "literal", value: 1 }); + }); + + it.each([ + "const [copy] = alias;", + "const copy = [...alias];", + "for (const copy of alias) {}", + ])("ignores iterable aliases replaced before %s", (iteration) => { + expect( + resultValue(` + const source = { *[Symbol.iterator]() { yield this; }, value: 1 }; + let alias = source; + alias = []; + ${iteration} + return source.value; + `), + ).toEqual({ status: "literal", value: 1 }); + }); + + it.each([ + ["const snapshot=source.value;", "snapshot"], + ["const {value:snapshot}=source;", "snapshot"], + ["const copy={value:source.value};", "copy.value"], + ['const copy={["snapshot"]:source.value};', "copy.snapshot"], + ['const copy={[""]:source.value};', 'copy[""]'], + ["const copy={[0]:source.value};", "copy[0]"], + ['const copy={[("snapshot" as string)]:source.value};', "copy.snapshot"], + ["const copy=[source.value];", "copy[0]"], + ])("preserves primitive capture before escape: %s", (capture, result) => { + expect( + resultValue( + `const source={value:1}; ${capture} mutate(source); return ${result};`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const source={value:1}; mutate(source); ${capture} return ${result};`, + )?.status, + ).toBe("unknown"); + }); + + it.each([ + ["const copy={value:source.value};", "copy.value"], + ["const copy=[source.value];", "copy[0]"], + ])( + "retains a literal field's earlier primitive capture: %s", + (copy, read) => { + expect( + resultValue( + `const source={value:1}; ${copy} mutate(source); const snapshot=${read}; mutate(copy); return snapshot;`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const source={value:1}; mutate(source); ${copy} const snapshot=${read}; mutate(copy); return snapshot;`, + )?.status, + ).toBe("unknown"); + }, + ); + + it.each([ + ["const copy={child:source.child};", "copy.child"], + ["const copy=[source.child];", "copy[0]"], + ])( + "keeps a shared child uncertain across both capture points: %s", + (copy, read) => { + expect( + resultValue( + `const source={child:{value:1}}; ${copy} mutate(source); const snapshot=${read}; mutate(copy); return snapshot.value;`, + )?.status, + ).toBe("unknown"); + }, + ); + + it.each([ + "const alias=source; const snapshot=alias.value; mutate(alias); return snapshot;", + "const alias=source.child; const snapshot=alias.value; mutate(alias); return snapshot;", + ])("captures through an earlier intermediate reference: %s", (body) => { + expect( + resultValue(`const source={value:1,child:{value:1}}; ${body}`), + ).toEqual({ status: "literal", value: 1 }); + }); + + it("does not read a later alias initializer at an earlier capture point", () => { + expect( + resultValue( + "const source={value:1}; var alias; const snapshot=alias?.value; mutate(source); alias=source; return snapshot;", + )?.status, + ).toBe("unknown"); + }); + + it("does not treat a persistent child as freshly allocated with its wrapper", () => { + const ir = analyzeJavaScriptSemantics( + "const child={value:1}; export function result(){const source={child}; const alias=source.child; const snapshot=alias.value; mutate(alias); return snapshot;}", + ); + expect(onlyCallable(ir, "result").returnSites[0]?.value.status).toBe( + "unknown", + ); + }); + + it("keeps persistent sources uncertain across function activations", () => { + const ir = analyzeJavaScriptSemantics( + "const source={value:1}; export function result(){const snapshot=source.value; mutate(source); return snapshot;}", + ); + expect(onlyCallable(ir, "result").returnSites[0]?.value.status).toBe( + "unknown", + ); + }); + + it("keeps reads from earlier loop iterations uncertain", () => { + expect( + resultValue( + "const source={value:1}; for(let i=0;i<2;i++){const snapshot=source.value; mutate(source); if(i===1)return snapshot;}", + )?.status, + ).toBe("unknown"); + }); + + it.each([ + "const copy={child:source.child}; return copy.child.value;", + "const copy=source.child; return copy.value;", + "const copy=[source.child]; return copy[0].value;", + ])("keeps shared children live: %s", (body) => { + expect( + resultValue( + `const source={child:{value:1}}; ${body.replace("return", "mutate(source); return")}`, + )?.status, + ).toBe("unknown"); + }); +}); + +describe("references captured before an intermediate rebind", () => { + it.each([ + ["const saved=alias;", "alias=saved;", "mutate(alias);"], + ["const saved=alias;", "alias=saved;", "alias.value=9;"], + ["const saved={child:alias};", "alias=saved.child;", "mutate(alias);"], + ["const {...saved}={child:alias};", "alias=saved.child;", "mutate(alias);"], + ["const [...saved]=[alias];", "alias=saved[0];", "mutate(alias);"], + ["const {saved=alias}={};", "alias=saved;", "mutate(alias);"], + ])("follows an alias restored from %s", (capture, restore, effect) => { + expect( + resultValue( + `const source={value:1}; let alias=source; ${capture} ${restore} ${effect} return source.value;`, + )?.status, + ).toBe("unknown"); + }); + + it.each([ + ["const saved=alias;", "mutate(saved);"], + ["const saved={child:alias};", "mutate(saved.child);"], + ["const {...saved}={child:alias};", "mutate(saved.child);"], + ["const [...saved]=[alias];", "mutate(saved[0]);"], + ["const {saved=alias}={};", "mutate(saved);"], + ["const [saved=alias]=[];", "mutate(saved);"], + ["const saved=alias;", "saved.method();"], + ["const saved=alias;", "mutate(alias,saved);"], + ["const saved=alias;", "mutate(saved,alias);"], + ])("preserves the original reference captured by %s", (capture, effect) => { + expect( + resultValue( + `const source={value:1}; let alias=source; ${capture} alias={}; ${effect} return source.value;`, + )?.status, + ).toBe("unknown"); + expect( + resultValue( + `const source={value:1}; let alias=source; alias={}; ${capture} ${effect} return source.value;`, + ), + ).toEqual({ status: "literal", value: 1 }); + }); + + it.each([ + [ + "let {...alias}={child:source};", + "alias={child:{}};", + "saved.child.value=9;", + ], + ["let [...alias]=[source];", "alias=[{}];", "saved[0].value=9;"], + ["let {alias=source}={};", "alias={};", "saved.value=9;"], + ["let [alias=source]=[];", "alias={};", "saved.value=9;"], + ])( + "preserves a saved rest/default reference from %s", + (declaration, rebind, effect) => { + expect( + resultValue( + `const source={value:1}; ${declaration} const saved=alias; ${rebind} ${effect} return source.value;`, + )?.status, + ).toBe("unknown"); + expect( + resultValue( + `const source={value:1}; ${declaration} ${rebind} const saved=alias; ${effect} return source.value;`, + ), + ).toEqual({ status: "literal", value: 1 }); + }, + ); +}); diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 7bdbdcc09..5a873429e 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -52,6 +52,19 @@ interface BindPatternInput { readonly mutable: boolean; readonly kind?: JavaScriptSemanticDefinition["kind"]; readonly projection?: readonly (string | number | null)[]; + readonly referenceOnly?: boolean; + readonly copyKind?: "object-rest" | "array-rest"; + readonly copyProjectionOffset?: number; + readonly copyExcludedKeys?: readonly string[]; + readonly copyStartIndex?: number; + readonly fallbackSources?: readonly { + readonly node: t.Node; + readonly projection: readonly (string | number | null)[]; + }[]; + readonly requiredSources?: readonly { + readonly node: t.Node; + readonly projection: readonly (string | number | null)[]; + }[]; } interface AddBindingInput { @@ -279,6 +292,7 @@ const createState = (program: t.Program): JavaScriptSemanticAnalysisState => { bindings: new Map(), }; return { + parentsByNode: new WeakMap(), scopes: [root], scopesById: new Map([[root.scopeId, root]]), scopeByNode: new WeakMap([[program, root]]), @@ -752,12 +766,36 @@ const bindPattern = (input: BindPatternInput): void => { mutable, kind = "variable", projection = [], + referenceOnly = false, + copyKind, + copyProjectionOffset, + copyExcludedKeys, + copyStartIndex, + fallbackSources, + requiredSources, } = input; if (t.isTSParameterProperty(pattern)) { bindPattern({ ...input, pattern: pattern.parameter }); return; } if (t.isIdentifier(pattern)) { + if (referenceOnly) { + const binding = scope.bindings.get(pattern.name); + if (binding !== undefined && initializer !== null) + binding.referenceInitializers.push({ + node: initializer, + projection, + ...(copyKind === undefined ? {} : { copyKind }), + ...(copyProjectionOffset === undefined + ? {} + : { copyProjectionOffset }), + ...(copyExcludedKeys === undefined ? {} : { copyExcludedKeys }), + ...(copyStartIndex === undefined ? {} : { copyStartIndex }), + ...(fallbackSources === undefined ? {} : { fallbackSources }), + ...(requiredSources === undefined ? {} : { requiredSources }), + }); + return; + } addBinding({ state, scope, @@ -778,6 +816,25 @@ const bindPattern = (input: BindPatternInput): void => { kind === "parameter" || kind === "catch" ? initializer : (initializer ?? pattern.right), + requiredSources: [ + ...(requiredSources ?? []), + ...(initializer === null ? [] : [{ node: initializer, projection }]), + ], + }); + bindPattern({ + state, + scope, + mutable, + kind, + pattern: pattern.left, + initializer: pattern.right, + projection: [], + referenceOnly: true, + fallbackSources: [ + ...(fallbackSources ?? []), + ...(initializer === null ? [] : [{ node: initializer, projection }]), + ], + ...(requiredSources === undefined ? {} : { requiredSources }), }); return; } @@ -792,7 +849,7 @@ const bindPattern = (input: BindPatternInput): void => { } if (t.isObjectPattern(pattern)) for (const property of pattern.properties) { - if (t.isRestElement(property)) + if (t.isRestElement(property)) { bindPattern({ ...input, pattern: property.argument, @@ -800,7 +857,23 @@ const bindPattern = (input: BindPatternInput): void => { mutable: true, projection: [], }); - else { + bindPattern({ + ...input, + pattern: property.argument, + projection: [...projection, null], + referenceOnly: true, + copyKind: "object-rest", + copyProjectionOffset: projection.length, + copyExcludedKeys: pattern.properties.flatMap((property) => { + if (t.isRestElement(property)) return []; + const key = semanticStaticPropertyKey( + property.key, + property.computed, + ); + return key === null ? [] : [key]; + }), + }); + } else { const name = semanticStaticPropertyKey(property.key, property.computed); bindPattern({ ...input, @@ -811,12 +884,23 @@ const bindPattern = (input: BindPatternInput): void => { } else if (t.isArrayPattern(pattern)) pattern.elements.forEach((element, index) => { - if (element !== null) + if (element !== null) { bindPattern({ ...input, pattern: element, projection: [...projection, index], }); + if (t.isRestElement(element)) + bindPattern({ + ...input, + pattern: element.argument, + projection: [...projection, null], + referenceOnly: true, + copyKind: "array-rest", + copyProjectionOffset: projection.length, + copyStartIndex: index, + }); + } }); }; @@ -858,8 +942,10 @@ const createBinding = ( kind, mutable, mutatedPaths: [], + escapedPaths: [], definitions: [], initializers: [], + referenceInitializers: [], directOrigins: [], }); diff --git a/src/domain/javascript/javascriptSemanticIterationSources.ts b/src/domain/javascript/javascriptSemanticIterationSources.ts new file mode 100644 index 000000000..1b9e7d714 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticIterationSources.ts @@ -0,0 +1,163 @@ +import * as t from "@babel/types"; + +import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; +import { semanticArrayIndex } from "./javascriptSemanticPropertyPaths.js"; + +interface IterationSourceValue { + readonly node: t.Node; + readonly projection: readonly (string | number | null)[]; +} + +/** An implicit iterator receiver, with guards for destructuring defaults. */ +export interface SemanticIterationSource extends IterationSourceValue { + readonly mutation: t.Node; + readonly fallbackSources?: readonly IterationSourceValue[]; + readonly requiredSources?: readonly IterationSourceValue[]; +} + +interface PatternSource extends IterationSourceValue { + // A rest binding is a fresh array whose children retain their source indices. + readonly restStartIndex?: number; +} + +interface SourceGuards { + readonly fallbackSources?: readonly IterationSourceValue[]; + readonly requiredSources?: readonly IterationSourceValue[]; +} + +const add = ( + sources: SemanticIterationSource[], + source: IterationSourceValue, + mutation: t.Node, + guards: SourceGuards, +): void => { + sources.push({ + node: source.node, + projection: source.projection, + mutation, + ...guards, + }); +}; +const project = ( + source: PatternSource | undefined, + key: string | number | null, +): PatternSource | undefined => { + if (source === undefined) return undefined; + const index = key === null ? null : semanticArrayIndex(key); + return { + node: source.node, + projection: [ + ...source.projection, + source.restStartIndex !== undefined && index !== null + ? source.restStartIndex + index + : key, + ], + }; +}; +interface PatternCollection { + readonly sources: SemanticIterationSource[]; + readonly mutation: t.Node; +} + +const visit = ( + context: PatternCollection, + pattern: t.Node, + source: PatternSource | undefined, + guards: SourceGuards = {}, +): void => { + const { sources, mutation } = context; + if (t.isTSParameterProperty(pattern)) { + visit(context, pattern.parameter, source, guards); + return; + } + if (t.isAssignmentPattern(pattern)) { + visit(context, pattern.left, source, { + ...guards, + requiredSources: [ + ...(guards.requiredSources ?? []), + ...(source === undefined ? [] : [source]), + ], + }); + visit( + context, + pattern.left, + { node: pattern.right, projection: [] }, + { + ...guards, + fallbackSources: [ + ...(guards.fallbackSources ?? []), + ...(source === undefined ? [] : [source]), + ], + }, + ); + return; + } + if (t.isObjectPattern(pattern)) { + for (const property of pattern.properties) { + // Object rest creates a fresh object and has no iterable binding pattern. + if (t.isRestElement(property)) continue; + visit( + context, + property.value, + project( + source, + semanticStaticPropertyKey(property.key, property.computed), + ), + guards, + ); + } + return; + } + if (t.isArrayPattern(pattern)) { + if (source !== undefined && source.restStartIndex === undefined) + add(sources, source, mutation, guards); + pattern.elements.forEach((element, index) => { + if (element === null) return; + if (t.isRestElement(element)) + visit( + context, + element.argument, + source === undefined + ? undefined + : { + node: source.node, + projection: source.projection, + restStartIndex: (source.restStartIndex ?? 0) + index, + }, + guards, + ); + else visit(context, element, project(source, index), guards); + }); + return; + } + if (t.isRestElement(pattern)) + visit(context, pattern.argument, undefined, guards); +}; + +/** Describe implicit iteration sources without deciding their runtime values. */ +export const semanticIterationSources = ( + node: t.Node, + parent: t.Node | null, +): readonly SemanticIterationSource[] => { + const sources: SemanticIterationSource[] = []; + const context = { sources, mutation: node }; + if (t.isVariableDeclarator(node) && node.init != null) + visit(context, node.id, { node: node.init, projection: [] }); + else if (t.isAssignmentExpression(node) && node.operator === "=") + visit(context, node.left, { node: node.right, projection: [] }); + else if (t.isForOfStatement(node)) { + add(sources, { node: node.right, projection: [] }, node, {}); + const source = { node: node.right, projection: [null] }; + if (t.isVariableDeclaration(node.left)) { + for (const declaration of node.left.declarations) + visit(context, declaration.id, source); + } else visit(context, node.left, source); + } else if (t.isSpreadElement(node) && t.isArrayExpression(parent)) + add(sources, { node: node.argument, projection: [] }, node, {}); + 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); + + return sources; +}; diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index c9fa49558..526e937ad 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -2,77 +2,268 @@ import * as t from "@babel/types"; import { resolveSemanticBindingState, - type JavaScriptSemanticAnalysisState, type JavaScriptSemanticBindingState, + type JavaScriptSemanticAnalysisState, } from "./javascriptSemanticState.js"; -import { evaluateSemanticBinding } from "./javascriptSemanticValues.js"; +import { + clearSemanticPrimitiveBindingValues, + evaluateSemanticBinding, + evaluateSemanticExpression, +} from "./javascriptSemanticValues.js"; +import { + semanticContainer, + semanticSlotAtPath, +} from "./javascriptSemanticSlots.js"; +import { semanticIterationSources } from "./javascriptSemanticIterationSources.js"; +import { semanticMutationInitializers } from "./javascriptSemanticMutationInitializers.js"; +import { + semanticArrayIndex, + semanticPropertyPathKeyMatches, + type JavaScriptSemanticPropertyPath, +} from "./javascriptSemanticPropertyPaths.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; import { semanticStaticPropertyKey, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; -type PropertyPath = readonly (string | number | null)[]; +type PropertyPath = JavaScriptSemanticPropertyPath; +type ValueEffect = "write" | "escape"; -/** Keep explicit property mutations outside the initializer-only value lattice. */ +/** Preserve uncertainty from property writes and references exposed to calls. */ export const collectSemanticMemberMutations = ( program: t.Program, state: JavaScriptSemanticAnalysisState, ): void => { - const parents = new WeakMap(); + const parents = state.parentsByNode; traverseJavaScriptAst(program, { enter: (node, parent) => { if (parent !== null) parents.set(node, parent); }, }); + const recordedEffects = new Set(); + const selections = new Map(); + let arrayIterationUnknown = false; + const pendingReferences: { + readonly initializer: JavaScriptSemanticBindingState["referenceInitializers"][number]; + readonly path: PropertyPath; + readonly bindings: ReadonlySet; + readonly effect: ValueEffect; + readonly mutation?: t.Node; + readonly originAt: t.Node | undefined; + }[] = []; + const iterableReferences: IterableReference[] = []; + const iterableReferenceKeys = new WeakMap>(); + const deferIterable = (reference: IterableReference): void => { + const keys = iterableReferenceKeys.get(reference.node) ?? new Set(); + const key = JSON.stringify([ + reference.projection, + reference.path, + reference.fallbackPath, + reference.effect, + reference.mutation?.start, + reference.mutation?.end, + reference.originAt?.start, + reference.originAt?.end, + reference.iterationOnly, + reference.requiredSources?.map((source) => [ + source.node.start, + source.node.end, + source.projection, + ]), + reference.fallbackSources?.map((source) => [ + source.node.start, + source.node.end, + source.projection, + ]), + [...reference.bindings].sort(compareUnicodeCodePoints), + ]); + if (keys.has(key)) return; + keys.add(key); + iterableReferenceKeys.set(reference.node, keys); + iterableReferences.push(reference); + }; const markValue = ( node: t.Node, path: PropertyPath, bindings: ReadonlySet, - mutation: t.Node, + effect: ValueEffect = "write", + mutation?: t.Node, + originAt: t.Node | undefined = mutation, ): void => { - const unwrapped = unwrapJavaScriptExpression(node).node; - if (unwrapped !== node) { - markValue(unwrapped, path, bindings, mutation); - return; - } - if (t.isIdentifier(node)) { - const binding = resolveSemanticBindingState(state, node, node.name); - if (binding === undefined || bindings.has(binding.bindingId)) return; - const value = evaluateSemanticBinding(binding, state); - if (value.status === "literal" || value.status === "union") return; - binding.mutatedPaths.push(path); - const nested = new Set([...bindings, binding.bindingId]); - for (const initializer of mutationInitializers( - binding, - mutation, - parents, - )) - markValue( - initializer.node, - [...initializer.projection, ...path], - nested, - mutation, + const pending = [{ node, path, bindings, originAt }]; + while (pending.length > 0) { + const current = pending.pop(); + if (current === undefined) break; + const expression = unwrapJavaScriptExpression(current.node).node; + if (t.isIdentifier(expression)) { + const binding = resolveSemanticBindingState( + state, + expression, + expression.name, ); - return; - } - if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) { - const members: (string | null)[] = []; - let current: t.Node = node; - while ( - t.isMemberExpression(current) || - t.isOptionalMemberExpression(current) + if (binding === undefined) { + if ( + (expression.name === "Array" && + (current.path[0] === "prototype" || current.path[0] === null)) || + (["globalThis", "global", "window", "self"].includes( + expression.name, + ) && + (current.path[0] === "Array" || current.path[0] === null) && + (current.path[1] === "prototype" || current.path[1] === null)) + ) + arrayIterationUnknown = true; + continue; + } + // An alias restored from a saved reference can revisit the same binding + // at an earlier capture. Only a repeated lifetime closes a cycle. + const lifetime = JSON.stringify([ + binding.bindingId, + current.originAt?.start, + current.originAt?.end, + ]); + if (current.bindings.has(lifetime)) continue; + // Union compatible copied-slot selections at each binding. Carrying every + // combination of exclusions through branch diamonds is exponential. + const selectorIndex = current.path.findIndex( + (key) => key !== null && typeof key === "object", + ); + let path = current.path; + const selector = path[selectorIndex]; + if (selector !== null && typeof selector === "object") { + const selectionIdentity = JSON.stringify([ + binding.bindingId, + effect, + path.map((key, index) => + index === selectorIndex + ? { startIndex: selector.startIndex } + : key, + ), + mutation?.start, + mutation?.end, + current.originAt?.start, + current.originAt?.end, + ]); + const previous = selections.get(selectionIdentity); + const excludedKeys = + previous === undefined + ? selector.excludedKeys + : previous.filter((key) => selector.excludedKeys.includes(key)); + if (previous !== undefined && excludedKeys.length === previous.length) + continue; + selections.set(selectionIdentity, excludedKeys); + path = path.map((key, index) => + index === selectorIndex ? { ...selector, excludedKeys } : key, + ); + } + const identity = JSON.stringify([ + binding.bindingId, + effect, + path, + mutation?.start, + mutation?.end, + current.originAt?.start, + current.originAt?.end, + ]); + if (recordedEffects.has(identity)) continue; + const value = + effect === "write" + ? evaluateSemanticBinding(binding, state) + : undefined; + const primitiveWrite = + value?.status === "literal" || value?.status === "union"; + recordedEffects.add(identity); + const nested = new Set([...current.bindings, lifetime]); + const origins = + current.originAt === undefined + ? binding + : semanticMutationInitializers(binding, current.originAt, parents); + if (!primitiveWrite) { + if (effect === "escape") + binding.escapedPaths.push({ path, node: mutation }); + else binding.mutatedPaths.push(path); + clearSemanticPrimitiveBindingValues(state); + for (const initializer of origins.initializers) + pending.push({ + node: initializer.node, + path: [...initializer.projection, ...path], + bindings: nested, + originAt: initializer.node, + }); + } + for (const initializer of origins.referenceInitializers) { + const copiedPath = copiedReferencePath(initializer, path, effect); + if (copiedPath === null) continue; + pendingReferences.push({ + initializer, + path: copiedPath, + bindings: nested, + effect, + originAt: initializer.node, + ...(mutation === undefined ? {} : { mutation }), + }); + } + } else if ( + t.isMemberExpression(expression) || + t.isOptionalMemberExpression(expression) ) { - members.push( - semanticStaticPropertyKey(current.property, current.computed), - ); - current = current.object; + pending.push({ + node: expression.object, + path: [ + semanticStaticPropertyKey(expression.property, expression.computed), + ...current.path, + ], + bindings: current.bindings, + originAt: current.originAt, + }); + } else { + if ( + t.isArrayExpression(expression) && + ((current.path[0] === "__proto__" && + (effect === "escape" || current.path.length > 1)) || + (current.path[0] === "constructor" && + current.path[1] === "prototype")) + ) + arrayIterationUnknown = true; + for (const value of referencedValues( + expression, + current.path, + effect, + )) { + if (value.iterableFallbackPath !== undefined) + deferIterable({ + node: value.node, + projection: [], + path: value.path, + fallbackPath: value.iterableFallbackPath, + bindings: current.bindings, + effect, + originAt: current.originAt, + ...(mutation === undefined ? {} : { mutation }), + }); + else + pending.push({ + ...value, + bindings: current.bindings, + originAt: current.originAt, + }); + } } - markValue(current, [...members.reverse(), ...path], bindings, mutation); - return; } - for (const value of referencedValues(node, path)) - markValue(value.node, value.path, bindings, mutation); + }; + const markEscaped = ( + node: t.Node, + mutation: t.Node, + path: PropertyPath = [], + ): void => markValue(node, path, new Set(), "escape", mutation); + const markReceiver = (callee: t.Node, mutation: t.Node): void => { + const expression = unwrapJavaScriptExpression(callee).node; + if ( + t.isMemberExpression(expression) || + t.isOptionalMemberExpression(expression) + ) + markEscaped(expression.object, mutation); }; const markTarget = (node: t.Node, mutation: t.Node): void => { if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) @@ -80,6 +271,7 @@ export const collectSemanticMemberMutations = ( node.object, [semanticStaticPropertyKey(node.property, node.computed)], new Set(), + "write", mutation, ); else if (t.isRestElement(node)) markTarget(node.argument, mutation); @@ -96,143 +288,245 @@ export const collectSemanticMemberMutations = ( } }; traverseJavaScriptAst(program, { - enter: (node) => { + enter: (node, parent) => { + for (const source of semanticIterationSources(node, parent)) + deferIterable({ + ...source, + path: source.projection, + fallbackPath: source.projection, + bindings: new Set(), + effect: "escape", + originAt: source.mutation, + iterationOnly: true, + }); if (t.isAssignmentExpression(node)) markTarget(node.left, node); else if (t.isUpdateExpression(node)) markTarget(node.argument, node); else if (t.isUnaryExpression(node, { operator: "delete" })) markTarget(node.argument, node); else if (t.isForOfStatement(node) || t.isForInStatement(node)) markTarget(node.left, node); + else if ( + t.isCallExpression(node) || + t.isOptionalCallExpression(node) || + t.isNewExpression(node) + ) { + for (const argument of node.arguments) + if (t.isSpreadElement(argument)) + deferIterable({ + node: argument.argument, + projection: [], + path: [null], + fallbackPath: [], + bindings: new Set(), + effect: "escape", + mutation: node, + originAt: node, + }); + else markEscaped(argument, node); + // Constructing a member does not pass its container as `this`. + if (!t.isNewExpression(node)) markReceiver(node.callee, node); + } else if (t.isTaggedTemplateExpression(node)) { + markReceiver(node.tag, node); + for (const expression of node.quasi.expressions) + markEscaped(expression, node); + } }, }); -}; - -interface StatementPosition { - readonly body: readonly t.Statement[]; - readonly index: number; -} - -const statementPosition = ( - statement: t.Statement, - parents: WeakMap, -): StatementPosition | null => { - const parent = parents.get(statement); - if (!t.isProgram(parent) && !t.isBlockStatement(parent)) return null; - const index = parent.body.indexOf(statement); - return index < 0 ? null : { body: parent.body, index }; -}; - -const directInitializerPosition = ( - node: t.Node, - parents: WeakMap, -): StatementPosition | null => { - const parent = parents.get(node); - if (t.isVariableDeclarator(parent) && parent.init === node) { - const declaration = parents.get(parent); - return t.isVariableDeclaration(declaration) - ? statementPosition(declaration, parents) - : null; - } - if ( - t.isAssignmentExpression(parent) && - parent.operator === "=" && - parent.right === node && - t.isIdentifier(parent.left) - ) { - const statement = parents.get(parent); - return t.isExpressionStatement(statement) && statement.expression === parent - ? statementPosition(statement, parents) - : null; - } - return null; -}; - -const directMutationPosition = ( - node: t.Node, - parents: WeakMap, -): StatementPosition | null => { - if ( - !t.isAssignmentExpression(node) && - !t.isUpdateExpression(node) && - !t.isUnaryExpression(node, { operator: "delete" }) - ) - return null; - const statement = parents.get(node); - return t.isExpressionStatement(statement) && statement.expression === node - ? statementPosition(statement, parents) - : null; -}; - -const mutationInitializers = ( - binding: JavaScriptSemanticBindingState, - mutation: t.Node, - parents: WeakMap, -): JavaScriptSemanticBindingState["initializers"] => { - if (binding.initializers.length < 2) return binding.initializers; - const mutationPosition = directMutationPosition(mutation, parents); - if (mutationPosition === null) return binding.initializers; - const positions = binding.initializers.map(({ node, entryBody }) => - entryBody === undefined - ? directInitializerPosition(node, parents) - : { body: entryBody.body, index: -1 }, - ); - if ( - positions.some( - (position) => - position === null || - position.body !== mutationPosition.body || - position.index >= mutationPosition.index, + // A later effect can make a previously defined destructuring source uncertain. + // Reconsider defaults and iterable origins until their effects are stable. + while (pendingReferences.length > 0 || iterableReferences.length > 0) { + const effectsBefore = recordedEffects.size; + const iterablesBefore = iterableReferences.length; + const iterationBefore: boolean = arrayIterationUnknown; + for (const reference of pendingReferences.splice(0)) { + const { initializer } = reference; + if (referenceSourcesInactive(initializer, state)) + pendingReferences.push(reference); + else if ( + initializer.copyKind === "array-rest" && + initializer.copyProjectionOffset !== undefined + ) { + const offset = initializer.copyProjectionOffset; + const projection = initializer.projection.slice(0, offset); + deferIterable({ + node: initializer.node, + projection, + path: reference.path, + fallbackPath: projection, + bindings: reference.bindings, + effect: reference.effect, + originAt: reference.originAt, + ...(reference.mutation === undefined + ? {} + : { mutation: reference.mutation }), + }); + } else + markValue( + initializer.node, + reference.path, + reference.bindings, + reference.effect, + reference.mutation, + reference.originAt, + ); + } + for (const reference of [...iterableReferences]) { + if (referenceSourcesInactive(reference, state)) continue; + if (reference.iterationOnly) { + const expanded = expandedIterationReferences(reference, state); + if (expanded !== null) { + for (const selected of expanded) deferIterable(selected); + continue; + } + } + const slot = selectedReferenceSlot(reference, state); + // Custom iteration can yield the iterable itself as well as any child. + // Treat its root as escaped, including writes through yielded references. + const knownArray = + !arrayIterationUnknown && + slot?.value.status === "array" && + slot.value.items.every( + (item) => semanticArrayIndex(item.name) !== null, + ); + if (knownArray && reference.iterationOnly) continue; + markValue( + reference.node, + knownArray ? reference.path : reference.fallbackPath, + reference.bindings, + knownArray ? reference.effect : "escape", + reference.mutation, + reference.originAt, + ); + } + if ( + recordedEffects.size === effectsBefore && + iterableReferences.length === iterablesBefore && + arrayIterationUnknown === iterationBefore ) - ) - return binding.initializers; - const latestIndex = positions.reduce( - (latest, position) => Math.max(latest, position?.index ?? -1), - -1, - ); - return binding.initializers.filter( - (_, index) => positions[index]?.index === latestIndex, - ); + break; + } + // Gathering effects can evaluate a primitive projection before its object + // escapes. Final values must use the completed mutation state. + clearSemanticPrimitiveBindingValues(state); }; interface ReferencedValue { readonly node: t.Node; readonly path: PropertyPath; + readonly iterableFallbackPath?: PropertyPath; } +interface IterableReference extends ReferencedValue { + readonly projection: PropertyPath; + readonly fallbackPath: PropertyPath; + readonly bindings: ReadonlySet; + readonly effect: ValueEffect; + readonly mutation?: t.Node; + readonly originAt: t.Node | undefined; + readonly iterationOnly?: boolean; + readonly requiredSources?: readonly { + readonly node: t.Node; + readonly projection: PropertyPath; + }[]; + readonly fallbackSources?: readonly { + readonly node: t.Node; + readonly projection: PropertyPath; + }[]; +} + +const referenceSourcesInactive = ( + reference: Pick, + state: JavaScriptSemanticAnalysisState, +): boolean => + reference.requiredSources?.some( + (source) => selectedReferenceSlot(source, state)?.presence === "absent", + ) === true || + reference.fallbackSources?.some((source) => { + const slot = selectedReferenceSlot(source, state); + return ( + slot?.presence === "present" && + (slot.value.status === "literal" || + slot.value.status === "union" || + slot.value.status === "object" || + slot.value.status === "array") + ); + }) === true; + +const expandedIterationReferences = ( + reference: IterableReference, + state: JavaScriptSemanticAnalysisState, +): readonly IterableReference[] | null => { + if (!t.isForOfStatement(reference.mutation)) return null; + const iterable = reference.mutation.right; + // Expand only the loop's yielded-item selector. Enumerating dynamic property + // selections would multiply paths through shared object aliases. + const source = [ + reference, + ...(reference.requiredSources ?? []), + ...(reference.fallbackSources ?? []), + ].find((source) => source.node === iterable && source.projection[0] === null); + if (source === undefined) return null; + const slot = selectedReferenceSlot({ node: iterable, projection: [] }, state); + const container = slot === undefined ? null : semanticContainer(slot.value); + if (container?.coverage.status !== "complete") return null; + const select = ( + candidate: { readonly node: t.Node; readonly projection: PropertyPath }, + name: string, + ) => ({ + ...candidate, + projection: + candidate.node === iterable && candidate.projection[0] === null + ? [name, ...candidate.projection.slice(1)] + : candidate.projection, + }); + return container.slots.map((slot) => { + const { projection } = select(reference, slot.name); + return { + ...reference, + projection, + path: projection, + fallbackPath: projection, + ...(reference.requiredSources === undefined + ? {} + : { + requiredSources: reference.requiredSources.map((source) => + select(source, slot.name), + ), + }), + ...(reference.fallbackSources === undefined + ? {} + : { + fallbackSources: reference.fallbackSources.map((source) => + select(source, slot.name), + ), + }), + }; + }); +}; + const referencedValues = ( node: t.Node, path: PropertyPath, + effect: ValueEffect, ): readonly ReferencedValue[] => { - const [key, ...remaining] = path; // An initializer owns its slots; only deeper writes can affect shared children. - if (t.isObjectExpression(node)) - return path.length < 2 - ? [] - : node.properties.flatMap((property) => { - if (t.isSpreadElement(property)) - return [{ node: property.argument, path }]; - if (!t.isObjectProperty(property)) return []; - const name = semanticStaticPropertyKey( - property.key, - property.computed, - ); - return key === null || name === null || String(key) === name - ? [{ node: property.value, path: remaining }] - : []; - }); - if (t.isArrayExpression(node)) { - if (path.length < 2) return []; - let uncertainIndex = false; - return node.elements.flatMap((element, index) => { - if (element === null) return []; - if (t.isSpreadElement(element)) { - uncertainIndex = true; - return [{ node: element.argument, path: [null, ...remaining] }]; - } - return uncertainIndex || key === null || String(key) === String(index) - ? [{ node: element, path: remaining }] - : []; - }); + if (t.isObjectExpression(node) || t.isArrayExpression(node)) { + if (effect === "write" && path.length < 2) return []; + return t.isObjectExpression(node) + ? objectReferencedValues(node, path) + : arrayReferencedValues(node, path); + } + if (t.isAssignmentExpression(node)) + return node.operator === "||=" || node.operator === "??=" + ? [ + { node: node.left, path }, + { node: node.right, path }, + ] + : [{ node: node.right, path }]; + if (t.isAwaitExpression(node)) return [{ node: node.argument, path }]; + if (t.isSequenceExpression(node)) { + const last = node.expressions.at(-1); + return last === undefined ? [] : [{ node: last, path }]; } if (t.isConditionalExpression(node)) return [ @@ -244,7 +538,169 @@ const referencedValues = ( { node: node.left, path }, { node: node.right, path }, ]; - if (t.isAssignmentExpression(node, { operator: "&&=" })) - return [{ node: node.right, path }]; return []; }; + +const objectReferencedValues = ( + node: t.ObjectExpression, + path: PropertyPath, +): readonly ReferencedValue[] => { + const [key, ...remaining] = path; + const references: ReferencedValue[] = []; + const overwritten = new Set(); + for (const property of [...node.properties].reverse()) { + if (t.isSpreadElement(property)) { + const selected = key ?? null; + if (typeof selected !== "object" && overwritten.has(String(selected))) + continue; + references.push({ + node: property.argument, + path: [ + typeof selected === "object" + ? { + ...(selected ?? {}), + excludedKeys: [ + ...new Set([ + ...(selected?.excludedKeys ?? []), + ...overwritten, + ]), + ].sort(compareUnicodeCodePoints), + } + : selected, + ...remaining, + ], + }); + continue; + } + const name = semanticStaticPropertyKey(property.key, property.computed); + if (name !== null && overwritten.has(name)) continue; + if ( + t.isObjectProperty(property) && + (name === null || semanticPropertyPathKeyMatches(key ?? null, name)) + ) + references.push({ node: property.value, path: remaining }); + // A prototype setter does not replace an own property from a spread. + if ( + name !== null && + !(t.isObjectMethod(property) && property.kind !== "method") && + !( + t.isObjectProperty(property) && + !property.computed && + !property.shorthand && + name === "__proto__" + ) + ) + overwritten.add(name); + } + return references; +}; + +const arrayReferencedValues = ( + node: t.ArrayExpression, + path: PropertyPath, +): readonly ReferencedValue[] => { + const [key, ...remaining] = path; + const selected = key ?? null; + const selectedIndex = + typeof selected === "object" ? null : semanticArrayIndex(selected); + if (typeof selected !== "object" && selectedIndex === null) return []; + const references: ReferencedValue[] = []; + let minimumIndex = 0; + let uncertainIndex = false; + for (const element of node.elements) { + if (t.isSpreadElement(element)) { + if (selectedIndex === null || selectedIndex >= minimumIndex) { + let sourceKey: PropertyPath[number] = null; + if (!uncertainIndex) { + if (selectedIndex !== null) sourceKey = selectedIndex - minimumIndex; + else if (selected !== null && typeof selected === "object") + sourceKey = { + excludedKeys: selected.excludedKeys.flatMap((name) => { + const index = semanticArrayIndex(name); + return index === null || index < minimumIndex + ? [] + : [String(index - minimumIndex)]; + }), + startIndex: Math.max( + 0, + (selected.startIndex ?? 0) - minimumIndex, + ), + }; + } + references.push({ + node: element.argument, + path: [sourceKey, ...remaining], + iterableFallbackPath: [], + }); + } + uncertainIndex = true; + continue; + } + if ( + element !== null && + (uncertainIndex + ? selectedIndex === null || selectedIndex >= minimumIndex + : semanticPropertyPathKeyMatches(selected, String(minimumIndex))) + ) + references.push({ node: element, path: remaining }); + minimumIndex++; + } + return references; +}; + +const copiedReferencePath = ( + initializer: JavaScriptSemanticBindingState["referenceInitializers"][number], + path: PropertyPath, + effect: ValueEffect, +): PropertyPath | null => { + const offset = initializer.copyProjectionOffset; + if (offset === undefined) return [...initializer.projection, ...path]; + const copiedPath = [...initializer.projection.slice(offset + 1), ...path]; + if (effect === "write" && copiedPath.length < 2) return null; + let [key, ...remaining] = copiedPath; + if (initializer.copyKind === "array-rest") { + const startIndex = initializer.copyStartIndex ?? 0; + if (key === undefined || key === null) + key = { excludedKeys: [], startIndex }; + else if (typeof key === "object") + key = { + excludedKeys: key.excludedKeys.flatMap((name) => { + const index = semanticArrayIndex(name); + return index === null ? [] : [String(index + startIndex)]; + }), + startIndex: (key.startIndex ?? 0) + startIndex, + }; + else { + const index = semanticArrayIndex(key); + if (index === null) return null; + key = index + startIndex; + } + } else { + const excludedKeys = initializer.copyExcludedKeys ?? []; + if (key === undefined || key === null) key = { excludedKeys }; + else if (typeof key === "object") + key = { + ...key, + excludedKeys: [...new Set([...key.excludedKeys, ...excludedKeys])].sort( + compareUnicodeCodePoints, + ), + }; + else if (excludedKeys.includes(String(key))) return null; + } + return [...initializer.projection.slice(0, offset), key, ...remaining]; +}; + +const selectedReferenceSlot = ( + source: { readonly node: t.Node; readonly projection: PropertyPath }, + state: JavaScriptSemanticAnalysisState, +) => { + const path: string[] = []; + for (const key of source.projection) { + if (key === null || typeof key === "object") return undefined; + path.push(String(key)); + } + return semanticSlotAtPath( + evaluateSemanticExpression(source.node, state), + path, + ); +}; diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.test.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.test.ts new file mode 100644 index 000000000..8f4049409 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.test.ts @@ -0,0 +1,63 @@ +import * as t from "@babel/types"; +import { describe, expect, it } from "vitest"; + +import { semanticMutationInitializers } from "./javascriptSemanticMutationInitializers.js"; +import type { JavaScriptSemanticBindingState } from "./javascriptSemanticState.js"; +import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; + +describe("parameter references copied into function body bindings", () => { + it.each([ + ["var arg = []; mutate(arg);", false], + ["mutate(arg); var arg = [];", true], + ["if (flag) { var arg = []; } mutate(arg);", true], + ])( + "retains the entry reference only when still reachable: %s", + (body, retained) => { + const program = parseJavaScriptSource( + `function result(arg = source) { ${body} }`, + )?.program; + const callable = program?.body[0]; + if (program === undefined || !t.isFunctionDeclaration(callable)) + throw new Error("Expected a parsed function declaration"); + const parameter = callable.params[0]; + if (!t.isAssignmentPattern(parameter) || !t.isIdentifier(parameter.left)) + throw new Error("Expected the source parameter binding"); + const parents = new WeakMap(); + let replacement: t.Node | undefined; + let mutation: t.Node | undefined; + traverseJavaScriptAst(program, { + enter: (node, parent) => { + if (parent !== null) parents.set(node, parent); + if (t.isVariableDeclarator(node) && node.init !== null) + replacement = node.init; + if (t.isCallExpression(node)) mutation = node; + }, + }); + if (replacement === undefined || mutation === undefined) + throw new Error("Expected a body initializer and subsequent effect"); + const entry = { + node: parameter.left, + projection: [], + entryBody: callable.body, + }; + const assigned = { node: replacement, projection: [] }; + const binding: JavaScriptSemanticBindingState = { + bindingId: "body:arg", + scopeId: "body", + name: "arg", + kind: "variable", + mutable: true, + mutatedPaths: [], + escapedPaths: [], + definitions: [], + initializers: [entry, assigned], + referenceInitializers: [], + directOrigins: [], + }; + const origins = semanticMutationInitializers(binding, mutation, parents); + expect(origins.initializers.includes(entry)).toBe(retained); + expect(origins.initializers).toContain(assigned); + }, + ); +}); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts new file mode 100644 index 000000000..d80d6b9ad --- /dev/null +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -0,0 +1,228 @@ +import * as t from "@babel/types"; + +import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; +import type { JavaScriptSemanticBindingState } from "./javascriptSemanticState.js"; + +interface StatementPosition { + readonly body: readonly t.Statement[]; + readonly index: number; +} + +const statementPosition = ( + statement: t.Statement, + parents: WeakMap, +): StatementPosition | null => { + const parent = parents.get(statement); + if (!t.isProgram(parent) && !t.isBlockStatement(parent)) return null; + const index = parent.body.indexOf(statement); + return index < 0 ? null : { body: parent.body, index }; +}; + +const directInitializerPosition = ( + node: t.Node, + parents: WeakMap, +): StatementPosition | null => { + const parent = parents.get(node); + if (t.isVariableDeclarator(parent) && parent.init === node) { + const declaration = parents.get(parent); + return t.isVariableDeclaration(declaration) + ? statementPosition(declaration, parents) + : null; + } + if ( + t.isAssignmentExpression(parent) && + parent.operator === "=" && + parent.right === node && + t.isIdentifier(parent.left) + ) { + const statement = parents.get(parent); + return t.isExpressionStatement(statement) && statement.expression === parent + ? statementPosition(statement, parents) + : null; + } + return null; +}; + +const directMutationPosition = ( + node: t.Node, + parents: WeakMap, +): StatementPosition | null => { + if (t.isForOfStatement(node)) return statementPosition(node, parents); + if (t.isVariableDeclarator(node)) { + const declaration = parents.get(node); + return t.isVariableDeclaration(declaration) + ? statementPosition(declaration, parents) + : null; + } + if (t.isSpreadElement(node)) { + const array = parents.get(node); + return t.isArrayExpression(array) + ? semanticCapturePosition(array, parents) + : null; + } + if ( + !t.isAssignmentExpression(node) && + !t.isUpdateExpression(node) && + !t.isUnaryExpression(node, { operator: "delete" }) && + !t.isCallExpression(node) && + !t.isOptionalCallExpression(node) && + !t.isNewExpression(node) && + !t.isTaggedTemplateExpression(node) + ) + return null; + const statement = parents.get(node); + return t.isExpressionStatement(statement) && statement.expression === node + ? statementPosition(statement, parents) + : null; +}; + +const referenceInitializerPosition = ( + node: t.Node, + parents: WeakMap, +): StatementPosition | null => { + // Defaults live inside the declaration pattern rather than its initializer. + let current = node; + while (true) { + const direct = directInitializerPosition(current, parents); + if (direct !== null) return direct; + const parent = parents.get(current); + if (parent === undefined || t.isStatement(parent) || t.isFunction(parent)) + return null; + if (t.isVariableDeclarator(parent)) { + const declaration = parents.get(parent); + return t.isVariableDeclaration(declaration) + ? statementPosition(declaration, parents) + : null; + } + current = parent; + } +}; + +/** Resolve origins at their use or capture, never at a later transitive effect. */ +export const semanticMutationInitializers = ( + binding: JavaScriptSemanticBindingState, + mutation: t.Node, + parents: WeakMap, +): Pick< + JavaScriptSemanticBindingState, + "initializers" | "referenceInitializers" +> => { + const mutationPosition = + directMutationPosition(mutation, parents) ?? + referenceInitializerPosition(mutation, parents); + if (mutationPosition === null) return binding; + const origins = [ + ...binding.initializers.map((initializer) => ({ + initializer, + position: + initializer.entryBody === undefined + ? directInitializerPosition(initializer.node, parents) + : { body: initializer.entryBody.body, index: -1 }, + })), + ...binding.referenceInitializers.map((initializer) => ({ + initializer, + position: referenceInitializerPosition(initializer.node, parents), + })), + ]; + if ( + origins.some( + ({ position }) => + position === null || + position.body !== mutationPosition.body || + position.index >= mutationPosition.index, + ) + ) + return binding; + const latestIndex = origins.reduce( + (latest, { position }) => Math.max(latest, position?.index ?? -1), + -1, + ); + const retained = new Set( + origins + .filter(({ position }) => position?.index === latestIndex) + .map(({ initializer }) => initializer), + ); + return { + initializers: binding.initializers.filter((initializer) => + retained.has(initializer), + ), + referenceInitializers: binding.referenceInitializers.filter((initializer) => + retained.has(initializer), + ), + }; +}; + +/** Locate a capture only in an unconditional declaration or literal initializer. */ +export const semanticCapturePosition = ( + node: t.Node, + parents: WeakMap, +): StatementPosition | null => { + let current = node; + while (true) { + const direct = directInitializerPosition(current, parents); + if (direct !== null) return direct; + const parent = parents.get(current); + if ( + t.isObjectProperty(parent) && + parent.value === current && + semanticStaticPropertyKey(parent.key, parent.computed) !== null + ) + current = parent; + else if (t.isObjectExpression(parent) || t.isArrayExpression(parent)) + current = parent; + else return null; + } +}; + +/** Intermediate values must themselves have been initialized before capture. */ +export const semanticBindingPrecedesCapture = ( + binding: JavaScriptSemanticBindingState, + capture: t.Node, + parents: WeakMap, +): boolean => { + const initializer = binding.initializers[0]; + if (binding.initializers.length !== 1 || initializer === undefined) + return false; + const sourcePosition = directInitializerPosition(initializer.node, parents); + const capturePosition = semanticCapturePosition(capture, parents); + return ( + sourcePosition !== null && + capturePosition !== null && + sourcePosition.body === capturePosition.body && + sourcePosition.index < capturePosition.index + ); +}; + +/** Ignore later escapes only while reading earlier references in one activation. */ +export const semanticEscapeFollowsCapture = ( + binding: JavaScriptSemanticBindingState, + capture: t.Node, + escape: t.Node | undefined, + parents: WeakMap, +): boolean => { + const initializer = binding.initializers[0]; + if ( + escape === undefined || + initializer === undefined || + !semanticBindingPrecedesCapture(binding, capture, parents) + ) + return false; + // A literal allocates here. Aliases are evaluated at the same capture point, + // so an outer/persistent origin still receives all of its own escape effects. + if ( + !t.isObjectExpression(initializer.node) && + !t.isArrayExpression(initializer.node) && + !t.isIdentifier(initializer.node) && + !t.isMemberExpression(initializer.node) && + !t.isOptionalMemberExpression(initializer.node) + ) + return false; + const capturePosition = semanticCapturePosition(capture, parents); + const escapePosition = directMutationPosition(escape, parents); + return ( + capturePosition !== null && + escapePosition !== null && + capturePosition.body === escapePosition.body && + capturePosition.index < escapePosition.index + ); +}; diff --git a/src/domain/javascript/javascriptSemanticMutationValues.ts b/src/domain/javascript/javascriptSemanticMutationValues.ts index 70a25a33c..dbbc9d457 100644 --- a/src/domain/javascript/javascriptSemanticMutationValues.ts +++ b/src/domain/javascript/javascriptSemanticMutationValues.ts @@ -1,9 +1,42 @@ -import type { JavaScriptSemanticValue } from "./javascriptSemanticValueTypes.js"; +import type { + JavaScriptSemanticProperty, + JavaScriptSemanticValue, +} from "./javascriptSemanticValueTypes.js"; +import { + semanticPropertyPathKeyMatches, + type JavaScriptSemanticPropertyPath, +} from "./javascriptSemanticPropertyPaths.js"; + +/** Invalidate escaped object references without rewriting their containing slots. */ +export const invalidateSemanticEscapedPath = ( + value: JavaScriptSemanticValue, + path: JavaScriptSemanticPropertyPath, +): JavaScriptSemanticValue => { + if (value.status !== "object" && value.status !== "array") return value; + const [key, ...remaining] = path; + if (key === undefined) + return { + status: "unknown", + reason: "This object reference may have been mutated by a call.", + }; + const invalidateChild = ( + property: JavaScriptSemanticProperty, + ): JavaScriptSemanticProperty => + semanticPropertyPathKeyMatches(key, property.name) + ? { + ...property, + value: invalidateSemanticEscapedPath(property.value, remaining), + } + : property; + return value.status === "object" + ? { ...value, properties: value.properties.map(invalidateChild) } + : { ...value, items: value.items.map(invalidateChild) }; +}; /** Invalidate only slots that an explicit mutation can affect. */ export const invalidateSemanticMutationPath = ( value: JavaScriptSemanticValue, - path: readonly (string | number | null)[], + path: JavaScriptSemanticPropertyPath, ): JavaScriptSemanticValue => { const [key, ...remaining] = path; const unknown: JavaScriptSemanticValue = { @@ -11,13 +44,20 @@ export const invalidateSemanticMutationPath = ( reason: "This property may have been mutated.", }; if (key === undefined || key === null) return unknown; - if (value.status === "object") { - const name = String(key); - const observed = value.properties.some( - (property) => property.name === name, + if (value.status === "object" || value.status === "array") { + if (value.status === "array" && key === "length") + return { + status: "array", + items: [], + unknownItems: true, + omittedItems: null, + }; + const slots = value.status === "object" ? value.properties : value.items; + const observed = slots.some((property) => + semanticPropertyPathKeyMatches(key, property.name), ); - const properties = value.properties.map((property) => - property.name === name + const properties = slots.map((property) => + semanticPropertyPathKeyMatches(key, property.name) ? { ...property, ...(remaining.length === 0 @@ -27,37 +67,15 @@ export const invalidateSemanticMutationPath = ( } : property, ); - if (!observed) - properties.push({ name, value: unknown, presence: "unknown-coverage" }); - return { ...value, properties }; - } - if (value.status === "array") { - const name = String(key); - // Array length writes can remove every index; ordinary named properties - // and sparse indices affect only their own slot. - if (name === "length") - return { - status: "array", - items: [], - unknownItems: true, - omittedItems: null, - }; - const observed = value.items.some((item) => item.name === name); - const items = value.items.map((item) => - item.name === name - ? { - ...item, - presence: - remaining.length === 0 - ? ("unknown-coverage" as const) - : item.presence, - value: invalidateSemanticMutationPath(item.value, remaining), - } - : item, - ); - if (!observed) - items.push({ name, presence: "unknown-coverage", value: unknown }); - return { ...value, items }; + if (!observed && typeof key !== "object") + properties.push({ + name: String(key), + value: unknown, + presence: "unknown-coverage", + }); + return value.status === "object" + ? { ...value, properties } + : { ...value, items: properties }; } return unknown; }; diff --git a/src/domain/javascript/javascriptSemanticPropertyPaths.ts b/src/domain/javascript/javascriptSemanticPropertyPaths.ts new file mode 100644 index 000000000..9bee0e9b7 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticPropertyPaths.ts @@ -0,0 +1,37 @@ +/** Slots retained by a shallow copy after exclusions or an array prefix. */ +export interface JavaScriptSemanticPropertySelection { + readonly excludedKeys: readonly string[]; + readonly startIndex?: number; +} + +/** Internal mutation path, including selected children of a shallow copy. */ +export type JavaScriptSemanticPropertyPath = readonly ( + | string + | number + | null + | JavaScriptSemanticPropertySelection +)[]; + +/** Read only canonical JavaScript array indices, excluding named properties. */ +export const semanticArrayIndex = (key: string | number): number | null => { + const index = Number(key); + return Number.isInteger(index) && + index >= 0 && + index < 4_294_967_295 && + String(index) === String(key) + ? index + : null; +}; + +/** Test an exact key, wildcard, or copied-slot selection against an own key. */ +export const semanticPropertyPathKeyMatches = ( + key: JavaScriptSemanticPropertyPath[number], + name: string, +): boolean => { + if (key === null) return true; + if (typeof key !== "object") return String(key) === name; + if (key.excludedKeys.includes(name)) return false; + if (key.startIndex === undefined) return true; + const index = semanticArrayIndex(name); + return index !== null && index >= key.startIndex; +}; diff --git a/src/domain/javascript/javascriptSemanticState.ts b/src/domain/javascript/javascriptSemanticState.ts index cd5f40e4b..28ca97371 100644 --- a/src/domain/javascript/javascriptSemanticState.ts +++ b/src/domain/javascript/javascriptSemanticState.ts @@ -1,5 +1,7 @@ import * as t from "@babel/types"; +import type { JavaScriptSemanticPropertyPath } from "./javascriptSemanticPropertyPaths.js"; + import type { JavaScriptModuleOrigin, JavaScriptSemanticDefinition, @@ -15,6 +17,16 @@ interface JavaScriptSemanticInitializer { readonly entryBody?: t.BlockStatement; } +/** Additional references from destructuring copies and possible defaults. */ +interface JavaScriptSemanticReferenceInitializer extends JavaScriptSemanticInitializer { + readonly copyKind?: "object-rest" | "array-rest"; + readonly copyProjectionOffset?: number; + readonly copyExcludedKeys?: readonly string[]; + readonly copyStartIndex?: number; + readonly fallbackSources?: readonly JavaScriptSemanticInitializer[]; + readonly requiredSources?: readonly JavaScriptSemanticInitializer[]; +} + /** Mutable binding state used only while constructing the immutable IR. */ export interface JavaScriptSemanticBindingState { readonly bindingId: string; @@ -22,9 +34,14 @@ export interface JavaScriptSemanticBindingState { readonly name: string; kind: JavaScriptSemanticDefinition["kind"]; mutable: boolean; - readonly mutatedPaths: (readonly (string | number | null)[])[]; + readonly mutatedPaths: JavaScriptSemanticPropertyPath[]; + readonly escapedPaths: { + readonly path: JavaScriptSemanticPropertyPath; + readonly node: t.Node | undefined; + }[]; readonly definitions: JavaScriptSemanticDefinition[]; readonly initializers: JavaScriptSemanticInitializer[]; + readonly referenceInitializers: JavaScriptSemanticReferenceInitializer[]; readonly directOrigins: JavaScriptModuleOrigin[]; } @@ -40,6 +57,7 @@ export interface JavaScriptSemanticScopeState { /** Shared state for semantic collection and evaluation. */ export interface JavaScriptSemanticAnalysisState { + readonly parentsByNode: WeakMap; readonly scopes: JavaScriptSemanticScopeState[]; readonly scopesById: Map; readonly scopeByNode: WeakMap; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 2c0b855a4..51dd8da71 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -1,8 +1,17 @@ import * as t from "@babel/types"; +import { + semanticCapturePosition, + semanticEscapeFollowsCapture, + semanticBindingPrecedesCapture, +} from "./javascriptSemanticMutationInitializers.js"; + import { semanticSlotAtPath } from "./javascriptSemanticSlots.js"; -import { invalidateSemanticMutationPath } from "./javascriptSemanticMutationValues.js"; +import { + invalidateSemanticEscapedPath, + invalidateSemanticMutationPath, +} from "./javascriptSemanticMutationValues.js"; import type { JavaScriptBindingProvenance } from "./javascriptSemanticIr.js"; import type { @@ -46,6 +55,7 @@ interface EvaluationContext { readonly state: JavaScriptSemanticAnalysisState; readonly bindings: ReadonlySet; readonly expressionDepth: number; + readonly capturePoint?: t.Node; readonly primitiveBindingValues: Map; } @@ -54,6 +64,25 @@ const primitiveBindingValuesByState = new WeakMap< Map >(); +const primitiveExpressionValuesByState = new WeakMap< + JavaScriptSemanticAnalysisState, + WeakMap +>(); + +const capturedBindingValuesByState = new WeakMap< + JavaScriptSemanticAnalysisState, + WeakMap> +>(); + +/** Discard primitive projections evaluated before mutation collection finished. */ +export const clearSemanticPrimitiveBindingValues = ( + state: JavaScriptSemanticAnalysisState, +): void => { + primitiveBindingValuesByState.delete(state); + capturedBindingValuesByState.delete(state); + primitiveExpressionValuesByState.delete(state); +}; + const primitiveBindingValuesFor = ( state: JavaScriptSemanticAnalysisState, ): Map => { @@ -115,6 +144,20 @@ const evaluateBinding = ( ): JavaScriptSemanticValue => { if (context.bindings.has(binding.bindingId)) return { status: "cycle", reason: `Alias cycle at ${binding.name}.` }; + if ( + context.capturePoint !== undefined && + !semanticBindingPrecedesCapture( + binding, + context.capturePoint, + context.state.parentsByNode, + ) + ) { + const { capturePoint: _capturePoint, ...liveContext } = context; + return evaluateBinding(binding, { + ...liveContext, + primitiveBindingValues: primitiveBindingValuesFor(context.state), + }); + } const cached = context.primitiveBindingValues.get(binding.bindingId); if (cached !== undefined) return cached; if (binding.initializers.length === 0) @@ -146,15 +189,41 @@ const evaluateBinding = ( if (initializer === undefined) return { status: "unknown", reason: "Missing binding initializer." }; const nested = nestedContext(context, binding.bindingId); - const value = projectValue( + let value = projectValue( evaluateExpression(initializer.node, nested), initializer.projection, ); - const projected = binding.mutatedPaths.reduce( + if (!isPrimitive(value)) { + const captureContext = primitiveCaptureContext(initializer.node, nested); + if (captureContext !== undefined) { + const captured = projectValue( + evaluateExpression(initializer.node, captureContext), + initializer.projection, + ); + if (isPrimitive(captured)) value = captured; + } + } + const mutated = binding.mutatedPaths.reduce( invalidateSemanticMutationPath, value, ); + const projected = binding.escapedPaths.reduce( + (value, escape) => + context.capturePoint !== undefined && + semanticEscapeFollowsCapture( + binding, + context.capturePoint, + escape.node, + context.state.parentsByNode, + ) + ? value + : invalidateSemanticEscapedPath(value, escape.path), + mutated, + ); + // Point-local memoization also bounds failed speculative captures. Only a + // primitive result is allowed back into ordinary value evaluation. if ( + context.capturePoint !== undefined || projected.status === "literal" || projected.status === "union" || (isSemanticResourceLimit(projected) && @@ -301,7 +370,7 @@ const evaluateObject = ( name, presence: "present", value: t.isObjectProperty(property) - ? evaluateExpression(property.value, nestedContext(context)) + ? evaluateCapturedExpression(property.value, nestedContext(context)) : { status: "unknown", reason: "Object method or accessor value is not a primitive.", @@ -351,7 +420,7 @@ const evaluateArray = ( items.push({ name: String(items.length), presence: "present", - value: evaluateExpression(element, nestedContext(context)), + value: evaluateCapturedExpression(element, nestedContext(context)), }); } return unknownItems @@ -648,9 +717,68 @@ const nestedContext = ( ): EvaluationContext => ({ state: context.state, primitiveBindingValues: context.primitiveBindingValues, + ...(context.capturePoint === undefined + ? {} + : { capturePoint: context.capturePoint }), expressionDepth: context.expressionDepth + 1, bindings: bindingId === undefined ? context.bindings : new Set([...context.bindings, bindingId]), }); + +const isPrimitive = (value: JavaScriptSemanticValue): boolean => + value.status === "literal" || value.status === "union"; + +const primitiveCaptureContext = ( + node: t.Node, + context: EvaluationContext, +): EvaluationContext | undefined => { + if ( + context.capturePoint !== undefined || + t.isObjectExpression(node) || + t.isArrayExpression(node) || + semanticCapturePosition(node, context.state.parentsByNode) === null + ) + return undefined; + let captures = capturedBindingValuesByState.get(context.state); + if (captures === undefined) { + captures = new WeakMap(); + capturedBindingValuesByState.set(context.state, captures); + } + let values = captures.get(node); + if (values === undefined) { + values = new Map(); + captures.set(node, values); + } + return { ...context, capturePoint: node, primitiveBindingValues: values }; +}; + +const evaluateCapturedExpression = ( + node: t.Node, + context: EvaluationContext, +): JavaScriptSemanticValue => { + // A literal field captures its primitive at construction, even when its + // containing object is subsequently read at another capture point. + let values = primitiveExpressionValuesByState.get(context.state); + const cached = values?.get(node); + if (cached !== undefined) return cached; + let value = evaluateExpression(node, context); + if (!isPrimitive(value)) { + const captureContext = primitiveCaptureContext(node, context); + if (captureContext !== undefined) { + const captured = evaluateExpression(node, captureContext); + if (isPrimitive(captured)) value = captured; + } + } + // Never publish values evaluated at somebody else's capture point. Like + // binding caches, these entries are discarded whenever effects change. + if (context.capturePoint === undefined && isPrimitive(value)) { + if (values === undefined) { + values = new WeakMap(); + primitiveExpressionValuesByState.set(context.state, values); + } + values.set(node, value); + } + return value; +}; diff --git a/src/server/registerApplicationTools/compareExportShapes.ts b/src/server/registerApplicationTools/compareExportShapes.ts index f8e26ae26..de811fd86 100644 --- a/src/server/registerApplicationTools/compareExportShapes.ts +++ b/src/server/registerApplicationTools/compareExportShapes.ts @@ -41,7 +41,9 @@ export const registerCompareJavaScriptExportShapesTool = ( const comparison = javaScriptExportShapeComparisonResultSchema.parse( result.value.normalized_result, ); - const unknown = comparison.summary.unknown > 0; + const unknown = + comparison.summary.unknown > 0 || + comparison.coverage.status !== "complete-within-inputs"; return recordResult( { ...options, delivery: server.delivery }, contract, diff --git a/src/server/registerApplicationTools/helpers.ts b/src/server/registerApplicationTools/helpers.ts index 8fcbcee56..dd881887b 100644 --- a/src/server/registerApplicationTools/helpers.ts +++ b/src/server/registerApplicationTools/helpers.ts @@ -31,12 +31,14 @@ const unknownRegistration = ( | "javascript-export-shape" | "source-to-bundle-comparison", ) => ({ - question: + // Scope unknown identity to the comparison while keeping exact replays stable. + question: `${ kind === "application-version-comparison" ? "Which application entities remain unmatched or ambiguous across these versions?" : kind === "source-to-bundle-comparison" ? "Which historical source files remain unmatched or ambiguously mapped to the shipped bundle?" - : "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?", + : "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?" + } (comparison ${evidence.evidence_id})`, severity: "medium" as const, domain: kind, supporting_evidence_ids: [evidence.evidence_id], diff --git a/tests/acceptance/applications/applicationWorkflowCli.test.ts b/tests/acceptance/applications/applicationWorkflowCli.test.ts index 3ea95f3af..9abbd4f0d 100644 --- a/tests/acceptance/applications/applicationWorkflowCli.test.ts +++ b/tests/acceptance/applications/applicationWorkflowCli.test.ts @@ -457,7 +457,205 @@ describe("application workflow CLI input", () => { }); }); +describe("application workflow CLI copy boundaries", () => { + it("compares source values excluded from escaped rest and spread copies", async () => { + const root = await createTestTempDirectory("rea-copy-boundary-cli-"); + temporary.push(root); + const sources = [ + `export default function make() { + function mutate(value) { value.changed = true; } + const objectRest = { only: { value: "TOKEN" } }; + const { only, ...restObject } = objectRest; + mutate(restObject); + const arrayRest = [{ value: "TOKEN" }]; + const [head, ...restArray] = arrayRest; + mutate(restArray); + const objectSpread = { child: { value: "TOKEN" } }; + const spreadObject = { ...objectSpread, child: {} }; + mutate(spreadObject.child); + const arraySpread = [{ value: "TOKEN" }]; + const spreadArray = [{}, ...arraySpread]; + mutate(spreadArray[0]); + return { + kind: "copy-boundary", + objectRest: objectRest.only.value, + arrayRest: arrayRest[0].value, + objectSpread: objectSpread.child.value, + arraySpread: arraySpread[0].value, + }; + }`, + `export default function make() { + return { + kind: "copy-boundary", + objectRest: "UPDATED", arrayRest: "UPDATED", + objectSpread: "UPDATED", arraySpread: "UPDATED", + }; + }`, + ]; + const [left, right] = await analyzeCliSources(root, sources); + const inputPath = join(root, "comparison.json"); + await writeFile( + inputPath, + JSON.stringify({ + left, + right, + left_module_path: "parser.mjs", + left_export_name: "default", + right_module_path: "parser.mjs", + right_export_name: "default", + }), + ); + const compared = await runCli([ + "compare-javascript-export-shapes", + inputPath, + "--json", + ]); + expect(compared).toMatchObject({ + normalized_result: { + summary: { added: 0, removed: 0, changed: 4, unknown: 0 }, + coverage: { status: "complete-within-inputs" }, + changes: expect.arrayContaining( + ["/arrayRest", "/arraySpread", "/objectRest", "/objectSpread"].map( + (path) => + expect.objectContaining({ + status: "changed", + path, + left: { availability: "literal", value: "TOKEN" }, + right: { availability: "literal", value: "UPDATED" }, + }), + ), + ), + }, + }); + }, 20_000); +}); + +describe("application workflow CLI and MCP capture lifetimes", () => { + it("compares captured primitives and source values after aliases are replaced", async () => { + const root = await createTestTempDirectory("rea-capture-lifetime-cli-"); + temporary.push(root); + const fields = [ + "rebound", + "rest", + "snapshot", + "destructured", + "objectSnapshot", + "arraySnapshot", + ]; + const sources = [ + `export default function make() { + function mutate(value) { value.value = "MUTATED"; } + const original = {value: "TOKEN"}; + let alias = original; + alias = {}; + mutate(alias); + const child = {value: "TOKEN"}; + let {...rest} = {child}; + rest = {child: {}}; + rest.child.value = "MUTATED"; + const source = {value: "TOKEN"}; + const snapshot = source.value; + const {value: destructured} = source; + const objectSnapshot = {value: source.value}; + const arraySnapshot = [source.value]; + mutate(source); + return { + kind: "capture-boundary", + rebound: original.value, rest: child.value, + snapshot, destructured, + objectSnapshot: objectSnapshot.value, arraySnapshot: arraySnapshot[0], + }; + }`, + `export default function make() { return ${JSON.stringify({ + kind: "capture-boundary", + ...Object.fromEntries(fields.map((field) => [field, "UPDATED"])), + })}; }`, + ]; + const [left, right] = await analyzeCliSources(root, sources); + // Execute the authored fixtures independently of static analysis. + for (const [index, value] of ["TOKEN", "UPDATED"].entries()) { + const { stdout } = await execute(process.execPath, [ + "--input-type=module", + "--eval", + "const module = await import(process.argv[1]); console.log(JSON.stringify(module.default()));", + join(root, String(index), "parser.mjs"), + ]); + expect(JSON.parse(stdout)).toEqual({ + kind: "capture-boundary", + ...Object.fromEntries(fields.map((field) => [field, value])), + }); + } + const input = { + left, + right, + left_module_path: "parser.mjs", + left_export_name: "default", + right_module_path: "parser.mjs", + right_export_name: "default", + }; + const inputPath = join(root, "comparison.json"); + await writeFile(inputPath, JSON.stringify(input)); + const expected = { + normalized_result: { + summary: { added: 0, removed: 0, changed: 6, unknown: 0 }, + coverage: { status: "complete-within-inputs" }, + changes: expect.arrayContaining( + fields.map((field) => + expect.objectContaining({ + path: `/${field}`, + status: "changed", + left: { availability: "literal", value: "TOKEN" }, + right: { availability: "literal", value: "UPDATED" }, + }), + ), + ), + }, + }; + expect( + await runCli(["compare-javascript-export-shapes", inputPath, "--json"]), + ).toMatchObject(expected); + expect(await compareThroughStdioMcp(input)).toMatchObject(expected); + }, 20_000); +}); + describe("application workflow CLI export Evidence", () => { + it("preserves uncertainty after a helper can mutate an awaited return object", async () => { + const root = await createTestTempDirectory("rea-awaited-export-shape-cli-"); + temporary.push(root); + const sources = [ + `export default async function make() { + const result = { kind: "record" }; + function mutate(value) { value.extra = 1; } + mutate(await result); + return result; + }`, + 'export default async function make() { return { kind: "record", extra: 1 }; }', + ]; + const [left, right] = await analyzeCliSources(root, sources); + const compared = await runCli([ + "compare-javascript-export-shapes", + JSON.stringify({ + left, + right, + left_module_path: "parser.mjs", + left_export_name: "default", + right_module_path: "parser.mjs", + right_export_name: "default", + }), + "--json", + ]); + expect(compared).toMatchObject({ + operation: "compare_javascript_export_shapes", + normalized_result: { + summary: { added: 0, removed: 0, changed: 0 }, + coverage: { status: "partial" }, + changes: expect.arrayContaining([ + expect.objectContaining({ status: "unknown" }), + ]), + }, + }); + }, 20_000); + it("compares exact export shapes from file-backed Evidence", async () => { const root = await createTestTempDirectory("rea-export-shape-cli-"); temporary.push(root); @@ -647,6 +845,54 @@ describe("application workflow CLI validation", () => { }, 20_000); }); +const compareThroughStdioMcp = async ( + input: Record, +): Promise => { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + cwd: process.cwd(), + env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" }, + stderr: "pipe", + }); + const client = new Client({ + name: "javascript-capture-parity", + version: "1", + }); + try { + await client.connect(transport); + const response = await client.callTool({ + name: "compare_javascript_export_shapes", + arguments: input, + }); + expect(response.isError).not.toBe(true); + return response.structuredContent; + } finally { + try { + await client.close(); + } finally { + await transport.close(); + } + } +}; + +const analyzeCliSources = ( + root: string, + sources: readonly string[], +): Promise => + Promise.all( + sources.map(async (source, index) => { + const applicationRoot = join(root, String(index)); + await mkdir(applicationRoot); + await writeFile(join(applicationRoot, "parser.mjs"), source); + return runCli([ + "analyze-javascript-application", + applicationRoot, + "--json", + ]); + }), + ); + const runCli = async ( arguments_: readonly string[], environment: Readonly> = {}, diff --git a/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts b/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts index 0039be5c1..ed429c35e 100644 --- a/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts +++ b/tests/boundary/filesystem/javascriptExportShapeComparison.test.ts @@ -348,6 +348,64 @@ describe("JavaScript export return-shape uncertain presence", () => { }); describe("JavaScript export matching uncertain projections", () => { + it.each([ + ["Object.assign", "Object.assign(result, { extra: 1 });"], + ["local helper", "mutate(result);"], + ["alias", "const alias = result; mutate(alias);"], + ["destructuring", "const { value } = { value: result }; mutate(value);"], + ["shared wrapper", "mutate({ value: result });"], + ["spread arguments", "mutate(...[result]);"], + ["optional call", "mutate?.(result);"], + ["constructor", "new Mutator(result);"], + ["tagged template", "tag`${result}`;"], + ])( + "does not infer an addition after %s can mutate the return value", + async (_description, invocation) => { + const graphs = await analyzeSources({ + left: ` + function mutate(value) { (value.value ?? value).extra = 1; } + function Mutator(value) { value.extra = 1; } + function tag(_strings, value) { value.extra = 1; } + export default function make() { + const result = { kind: "record" }; + ${invocation} + return result; + } + `, + right: 'export default () => ({ kind: "record", extra: 1 });', + }); + const result = compare(...graphs); + expect(result.summary).toMatchObject({ + added: 0, + removed: 0, + changed: 0, + }); + expect(result.coverage.status).toBe("partial"); + expect(result.changes).toEqual( + expect.arrayContaining([ + expect.objectContaining({ status: "unknown" }), + ]), + ); + }, + ); + + it("keeps sibling properties known when a method can mutate its receiver", async () => { + const graphs = await analyzeSources({ + left: `export default function make() { + const result = { kind: "record", tokens: [] }; + result.tokens.push({ extra: 1 }); + return result; + }`, + right: + 'export default () => ({ kind: "record", tokens: [{ extra: 1 }] });', + }); + const result = compare(...graphs); + expect(result.summary).toMatchObject({ added: 0, removed: 0, changed: 0 }); + expect(result.coverage.status).toBe("partial"); + for (const inventory of result.property_inventories) + expect(inventory.properties).toContain("/kind"); + }); + it.each(["delete result.count;", "result.count = query();"])( "omits matching uncertain projections after %s", async (mutation) => { diff --git a/tests/boundary/mcp/applicationExportShapeMcp.test.ts b/tests/boundary/mcp/applicationExportShapeMcp.test.ts index 8ba6bc0bf..e336e3f74 100644 --- a/tests/boundary/mcp/applicationExportShapeMcp.test.ts +++ b/tests/boundary/mcp/applicationExportShapeMcp.test.ts @@ -12,6 +12,7 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; import { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "../../../src/contracts/javascript/javascriptExportShapeComparisonExample.js"; it("executes the advertised export presence example with matching analyzed Evidence", async () => { @@ -253,7 +254,161 @@ describe("application workflow MCP parity", () => { }); }); +describe("repeated partial export comparisons", () => { + it.each(["inline", "retained"] as const)( + "retains distinct partial comparisons and idempotent concurrent repeats with %s Evidence", + async (mode) => { + const pairs = await Promise.all( + Array.from({ length: 4 }, async (_, index) => { + const source = `export default function make() { + const result = { kind: "record-${index}", count: 1 }; + delete result.count; + return result; + } + export { make as named };`; + const [left, right] = await Promise.all([ + analyzeSourceEvidence(source), + analyzeSourceEvidence(source), + ]); + return { left, right }; + }), + ); + const { client, session, close } = await createApplicationMcpHarness(); + onTestFinished(close); + if (mode === "retained") + for (const { left, right } of pairs) + for (const evidence of [left, right]) + expect(session.recordEvidence(evidence).ok).toBe(true); + const compare = async ( + pair: (typeof pairs)[number], + exportName = "default", + ) => { + const response = await client.callTool({ + name: "compare_javascript_export_shapes", + arguments: { + left: + mode === "inline" + ? pair.left + : { + kind: "retained-evidence", + evidence_id: pair.left.evidence_id, + }, + right: + mode === "inline" + ? pair.right + : { + kind: "retained-evidence", + evidence_id: pair.right.evidence_id, + }, + left_module_path: "parser.mjs", + left_export_name: exportName, + right_module_path: "parser.mjs", + right_export_name: exportName, + }, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const evidence = parseEvidence(response.structuredContent); + expect(evidence.normalized_result).toMatchObject({ + changes: [], + coverage: { status: "partial" }, + }); + return evidence.evidence_id; + }; + const [firstPair, secondPair, ...remaining] = pairs; + if (firstPair === undefined || secondPair === undefined) + throw new Error("Expected distinct comparison fixtures"); + const firstId = await compare(firstPair); + const firstUnknowns = session.listUnknowns({ + domain: "javascript-export-shape", + }); + expect(firstUnknowns).toHaveLength(1); + const secondId = await compare(secondPair); + expect(secondId).not.toBe(firstId); + const selectedId = await compare(firstPair, "named"); + expect(selectedId).not.toBe(firstId); + const concurrentIds = await Promise.all( + [firstPair, secondPair, ...remaining, ...remaining].map((pair) => + compare(pair), + ), + ); + expect(concurrentIds.slice(0, 2)).toEqual([firstId, secondId]); + const evidenceIds = new Set([ + firstId, + secondId, + selectedId, + ...concurrentIds, + ]); + expect(evidenceIds.size).toBe(pairs.length + 1); + const unknowns = session.listUnknowns({ + domain: "javascript-export-shape", + }); + expect(unknowns).toHaveLength(pairs.length + 1); + expect(unknowns).toEqual(expect.arrayContaining(firstUnknowns)); + expect( + new Set( + unknowns.flatMap( + ({ supporting_evidence_ids }) => supporting_evidence_ids, + ), + ), + ).toEqual(evidenceIds); + expect(unknowns.every(({ revision }) => revision === 1)).toBe(true); + const records = session.exportEvidenceBundle().records; + for (const id of evidenceIds) + expect(records.some(({ evidence_id }) => evidence_id === id)).toBe( + true, + ); + const retained = session.exportEvidenceBundle(); + await Promise.all(pairs.map((pair) => compare(pair))); + expect(session.exportEvidenceBundle()).toEqual(retained); + }, + ); +}); + describe("source-produced export comparison inventories", () => { + it("records partial comparison coverage even when matching unknown projections produce no changes", async () => { + const source = `export default function make() { + const result = { kind: "record", count: 1 }; + delete result.count; + return result; + }`; + const [left, right] = await Promise.all([ + analyzeSourceEvidence(source), + analyzeSourceEvidence(source), + ]); + const { client, session, close } = await createApplicationMcpHarness(); + onTestFinished(close); + const response = await client.callTool({ + name: "compare_javascript_export_shapes", + arguments: { + left, + right, + left_module_path: "parser.mjs", + left_export_name: "default", + right_module_path: "parser.mjs", + right_export_name: "default", + }, + }); + expect(response.isError).not.toBe(true); + expect(response.structuredContent).toMatchObject({ + normalized_result: { + changes: [], + summary: { added: 0, removed: 0, changed: 0, unknown: 0 }, + coverage: { status: "partial" }, + }, + }); + const { evidence_id: evidenceId } = z + .object({ evidence_id: z.string() }) + .parse(response.structuredContent); + expect(session.exportEvidenceBundle().unknowns).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + domain: "javascript-export-shape", + supporting_evidence_ids: [evidenceId], + }), + ]), + ); + }); + it("retains large source-produced export inventories through comparison schemas", async () => { const fields = Array.from( { length: 64 }, From 73a664bc78ee618045a2733b8714821281f77403 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:58:29 +0200 Subject: [PATCH 121/189] fix(ghidra): verify dense jump tables on an optimized fixture (#1374) The dense jump-table oracles (inspect-native-api CLI and the analyze_function dossier) ran against the -O0 debug fixture, which assumes the host compiler lowers dense switches to tables at -O0. GCC 16 and later expand them as compare chains instead, so on those hosts the lane rejected a correct provider and Ghidra build with empty jump_tables. Build the same inventory source once more at -O2 as a dedicated jump-table variant, run both strict dense oracles there, and keep the debug dossier at its complete generic shape. The dedicated switch lane already compiles at -O2 for the same reason. --- scripts/verify-real-ghidra-function.mjs | 30 ++++++++++++----- scripts/verify-real-ghidra.mjs | 43 ++++++++++++++++++------- 2 files changed, 53 insertions(+), 20 deletions(-) diff --git a/scripts/verify-real-ghidra-function.mjs b/scripts/verify-real-ghidra-function.mjs index 8200f3f2e..b9d9c299e 100644 --- a/scripts/verify-real-ghidra-function.mjs +++ b/scripts/verify-real-ghidra-function.mjs @@ -153,14 +153,15 @@ export async function verifyDebugFunctionOperations( const denseSwitchDossier = await functionCall(client, "analyze_function", { procedure: denseSwitchProcedure.address, }); - if (process.platform === "linux" && process.arch === "x64") - assertDenseSwitchDossier(denseSwitchDossier, denseSwitchProcedure.address); - else - assertDossier(denseSwitchDossier, { - address: denseSwitchProcedure.address, - requireAssembly: true, - requireMultiBlock: true, - }); + // The debug fixture is compiled -O0, and GCC 16 and later lower dense + // switches to compare chains at -O0, so this dossier asserts only its + // complete shape; the optimized jump-table variant proves dense jump-table + // completeness through assertDenseSwitchDossier. + assertDossier(denseSwitchDossier, { + address: denseSwitchProcedure.address, + requireAssembly: true, + requireMultiBlock: true, + }); assertIndirectDossier(indirectDossier, leaf.address); const { cancellation, timeout } = await verifyRequestCancellationAndTimeout( @@ -372,6 +373,19 @@ async function verifyConcurrentRequests(client, entry, leaf) { return "serialized-two-results"; } +/** Prove dense jump-table completeness on the optimized jump-table fixture. */ +export async function verifyJumpTableDenseSwitch(client, procedures) { + const denseSwitchProcedure = requireProcedure( + procedures, + "rea_ghidra_inventory_dense_switch", + ); + const dossier = await functionCall(client, "analyze_function", { + procedure: denseSwitchProcedure.address, + }); + assertDenseSwitchDossier(dossier, denseSwitchProcedure.address); + return { dense_switch: dossierSummary(dossier) }; +} + export async function verifyStrippedFunctionOperations(client, entryString) { const stringXrefs = await functionCall(client, "xrefs", { document: null, diff --git a/scripts/verify-real-ghidra.mjs b/scripts/verify-real-ghidra.mjs index 59698f9c2..2ed9b0013 100644 --- a/scripts/verify-real-ghidra.mjs +++ b/scripts/verify-real-ghidra.mjs @@ -35,6 +35,7 @@ import { hasTypedSwitchEvidence } from "./verify-real-ghidra-switch-assertions.m import { verifyDenseDefaultReturn, + verifyJumpTableDenseSwitch, verifyNativeTypeLayout, verifyRelativeSwitch, verifyNativeValueTrace, @@ -80,6 +81,7 @@ const crossFormatSourcePath = fileURLToPath( const debugPath = join(fixtureRoot, "rea-ghidra-inventory-debug"); const layoutPath = join(fixtureRoot, "rea-ghidra-layout.o"); const strippedPath = join(fixtureRoot, "rea-ghidra-inventory-stripped"); +const jumpTablePath = join(fixtureRoot, "rea-ghidra-inventory-jump"); const arm64ElfPath = join(fixtureRoot, "rea-ghidra-cross-arm64"); const peObjectPath = join(fixtureRoot, "rea-ghidra-cross-x86_64.obj"); const pePath = join(fixtureRoot, "rea-ghidra-cross-x86_64.exe"); @@ -134,6 +136,14 @@ try { if (expectedNativeTarget.format === "mach-o") strippedFlags.push("-fvisibility=hidden"); await exec(compiler, [...strippedFlags, sourcePath, "-o", strippedPath]); + // The dense jump-table oracle needs the switch lowered to a table: GCC 16 and + // later expand dense switches as compare chains at -O0, so the CLI oracle + // runs against an optimized build while the debug fixture keeps its -O0 + // stack-local and DWARF shape. + const jumpTableFlags = ["-O2", "-g", "-fno-inline"]; + if (expectedNativeTarget.format === "elf") + jumpTableFlags.push("-fno-pie", "-no-pie"); + await exec(compiler, [...jumpTableFlags, sourcePath, "-o", jumpTablePath]); const crossTargets = []; if (aarch64JumpTableOnly) { const relativeSource = fileURLToPath( @@ -253,6 +263,11 @@ try { expectedNativeTarget, ); assertStrippedFixture(stripped); + const jumpTable = await verifyTarget( + jumpTablePath, + "jump-table", + expectedNativeTarget, + ); const crossResults = []; for (const [targetPath, variant, expectedTarget] of crossTargets) { const result = await verifyTarget(targetPath, variant, expectedTarget); @@ -277,11 +292,13 @@ try { crossFormat || aarch64JumpTableOnly ? [sourcePath, crossFormatSourcePath] : [sourcePath], - fixtures: [debug, stripped, layout, ...crossResults].map(summary), + fixtures: [debug, stripped, layout, jumpTable, ...crossResults].map( + summary, + ), malformed_target: "rejected-before-provider-start", native_api_cli: aarch64JumpTableOnly ? (crossResults[0]?.native_api_cli ?? null) - : debug.native_api_cli, + : jumpTable.native_api_cli, native_value_e2e: debug.native_values, custom_target: custom === null ? null : summary(custom), cleanup: "complete", @@ -493,7 +510,7 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) { const crossArm64Elf = variant === "cross-arm64-elf" || variant === "aarch64-jump-table"; const nativeApiCli = - variant === "debug" || crossArm64Elf + variant === "jump-table" || crossArm64Elf ? await verifyNativeApiCli(parsedTarget.value.path, procedures, { requireDenseJumpTable: crossArm64Elf || @@ -513,15 +530,17 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) { ) : variant === "type-layout" ? await verifyNativeTypeLayout(client, names) - : variant === "custom" || variant === "aarch64-jump-table" - ? null - : await verifyInventoryOperations({ - client, - variant, - procedures, - names, - strings, - }); + : variant === "jump-table" + ? await verifyJumpTableDenseSwitch(client, procedures) + : variant === "custom" || variant === "aarch64-jump-table" + ? null + : await verifyInventoryOperations({ + client, + variant, + procedures, + names, + strings, + }); const nativeValues = variant === "debug" ? await verifyNativeValueTrace(client, procedures, parsedTarget.value) From 39dabd0608ed9617d60f16ece05993089f24ff38 Mon Sep 17 00:00:00 2001 From: fernando Date: Fri, 9 Oct 2026 20:03:12 -0300 Subject: [PATCH 122/189] fix(mcp): advertise object roots for union input schemas (#1373) * fix(mcp): advertise object roots for union input schemas Anthropic tool input schemas reject anyOf, oneOf, and allOf at the root. Since 63bf9140 removed root flattening, compare_web_captures, inspect_web_page, inspect_electron_page, and project_managed_application_graph advertised root unions: Claude Desktop disabled compare_web_captures and Claude Code exposed the tools without parameters. Present a root union of plain-reference object branches as one strict object with the union of properties, shared required fields, a minProperties bound, and a description of the accepted input groups. The canonical Zod union still validates every call, so mixed input groups are rejected before the handler runs. Branches whose reference siblings cannot be merged keep their root alternatives. Co-Authored-By: Claude Opus 5.5 * test(browser): keep comparison input boundary within lint limits Express advertised and runtime expectations as one case table so the boundary test stays under the 150-line function limit. Co-Authored-By: Claude Opus 5.5 * fix(mcp): preserve input group dependencies in object schemas --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/mcp-contracts.md | 25 ++-- src/contracts/inputSchemaPresentation.ts | 125 +++++++++++++++++- src/contracts/toolInputReferences.test.ts | 106 +++++++++------ .../mcp/browserComparisonInput.test.ts | 114 ++++++++++------ tests/boundary/mcp/toolSchemaValidity.test.ts | 13 +- 5 files changed, 282 insertions(+), 101 deletions(-) diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index f25ea8a57..66487bd01 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -25,12 +25,16 @@ health transition leaves that catalog unchanged and does not emit Advertised input and output schemas contain no reachable recursive references. Schemas share repeated definitions through schema-local references while -preserving complete fields and validation rules. Input properties retain their -descriptions and literal examples. The SDK advertises an object root for -canonical object unions and retains each branch's requirements and exclusions. -Tests validate the schemas after SDK conversion and compare advertised -validation with actual calls. Individual model APIs can impose additional -nesting limits; complete producer captures can exceed ten structural levels. +preserving complete nested fields and validation rules. Input properties retain +their descriptions and literal examples. Root object unions are presented as +one object without root `anyOf`, `oneOf`, or `allOf` for model API compatibility. +The projection merges properties, retains shared required fields and +group-specific field dependencies, and describes the accepted input groups. +Canonical runtime validation enforces the exact union, including exclusions +that the advertised projection does not express. Tests validate the schemas +after SDK conversion and check advertised validation and actual calls. +Individual model APIs can impose additional nesting limits; complete producer +captures can exceed ten structural levels. `compare_web_captures` accepts exactly one of two input shapes: @@ -42,10 +46,11 @@ nesting limits; complete producer captures can exceed ten structural levels. `normalization` defaults to `{ "rules": [] }`. The advertised schema includes complete nested capture fields and rejects -incomplete pairs, mixed comparison families, and structurally malformed -captures. Domain validation additionally checks relationships such as event -sequence references and retained counts; JSON Schema does not express those -cross-field invariants. +incomplete pairs and structurally malformed captures. Mixed comparison families +can pass advertised validation; the SDK rejects them against the canonical +input schema before invoking the handler. Domain validation additionally checks +relationships such as event sequence references and retained counts; JSON +Schema does not express those cross-field invariants. Call `binary_session` with `{}` and read `result.tool_availability` to choose a callable operation for the current target, provider, host, and negotiated client diff --git a/src/contracts/inputSchemaPresentation.ts b/src/contracts/inputSchemaPresentation.ts index 6eae1989c..8b1bd5b9e 100644 --- a/src/contracts/inputSchemaPresentation.ts +++ b/src/contracts/inputSchemaPresentation.ts @@ -1,3 +1,5 @@ +import { isDeepStrictEqual } from "node:util"; + const schemaMaps = new Set([ "$defs", "definitions", @@ -102,11 +104,128 @@ const describeSchema = ( ); }; -/** Describe canonical input fields without changing structural constraints. */ +const objectBranch = ( + root: Readonly>, + branch: unknown, +): Readonly> | undefined => { + // Reference siblings evaluate separately from the target in 2020-12, so a + // merged object could accept inputs the branch rejects. + const resolved = + isObject(branch) && typeof branch.$ref === "string" + ? Object.keys(branch).length === 1 + ? resolveReference(root, branch.$ref) + : undefined + : branch; + return isObject(resolved) && + resolved.type === "object" && + isObject(resolved.properties) + ? resolved + : undefined; +}; + +const requiredProperties = ( + branch: Readonly>, +): readonly string[] => + Array.isArray(branch.required) + ? branch.required.filter((name) => typeof name === "string") + : []; + +const sharedRequiredProperties = ( + branches: readonly Readonly>[], +): readonly string[] => { + const [first = [], ...others] = branches.map(requiredProperties); + return first.filter((name) => others.every((names) => names.includes(name))); +}; + +const inputGroup = (branch: Readonly>): string => { + const required = requiredProperties(branch); + const optional = Object.keys(branch.properties ?? {}) + .filter((name) => !required.includes(name)) + .map((name) => `[${name}]`); + return [...required, ...optional].join(" + "); +}; + +// Anthropic tool input schemas reject anyOf, oneOf, and allOf at the root, and +// clients then drop the tool or advertise it without parameters. Present a +// root union of strict object groups as one object whose properties are the +// union of the groups. The canonical Zod schema still enforces the exact group. +const flattenRootObjectUnion = ( + root: Record, +): Record => { + const { anyOf, oneOf, ...rest } = root; + const alternatives = Array.isArray(anyOf) ? anyOf : oneOf; + if ( + !Array.isArray(alternatives) || + alternatives.length === 0 || + root.properties !== undefined + ) + return root; + const branches = alternatives.map((branch) => objectBranch(root, branch)); + if (!branches.every((branch) => branch !== undefined)) return root; + const variants = new Map(); + for (const branch of branches) + for (const [name, schema] of Object.entries(branch.properties ?? {})) { + const known = variants.get(name) ?? []; + if (!known.some((seen) => isDeepStrictEqual(seen, schema))) + known.push(schema); + variants.set(name, known); + } + const required = sharedRequiredProperties(branches); + // A field unique to a group still needs that group's required partners. + // Counting properties alone would let optional fields pad an incomplete pair. + const dependencies = Object.fromEntries( + [...variants.keys()].flatMap((name) => { + const owners = branches.filter((branch) => + Object.hasOwn(branch.properties ?? {}, name), + ); + const partners = sharedRequiredProperties(owners).filter( + (partner) => partner !== name && !required.includes(partner), + ); + return partners.length > 0 ? [[name, partners]] : []; + }), + ); + const fewestRequired = Math.min( + ...branches.map((branch) => requiredProperties(branch).length), + ); + // Groups that differ only in property values add no caller guidance. + const groups = [...new Set(branches.map(inputGroup))]; + const description = [ + typeof rest.description === "string" ? rest.description : undefined, + groups.length > 1 + ? `Provide a complete input group: ${groups.join("; ")}.` + : undefined, + ].filter((text) => text !== undefined); + return { + ...rest, + type: "object", + ...(description.length > 0 ? { description: description.join(" ") } : {}), + properties: Object.fromEntries( + [...variants].map(([name, schemas]) => [ + name, + schemas.length === 1 ? schemas[0] : { anyOf: schemas }, + ]), + ), + ...(required.length > 0 ? { required } : {}), + ...(fewestRequired > 0 ? { minProperties: fewestRequired } : {}), + ...(Object.keys(dependencies).length > 0 + ? { + [root.$schema === "http://json-schema.org/draft-07/schema#" + ? "dependencies" + : "dependentRequired"]: dependencies, + } + : {}), + ...(branches.every((branch) => branch.additionalProperties === false) + ? { additionalProperties: false } + : {}), + }; +}; + +/** Describe canonical input fields and present the root as one object. */ export const presentInputJsonSchema = ( root: Record, describeProperty: (property: string) => string, ): Record => { - const described = describeSchema(root, root, describeProperty); - return isObject(described) ? described : root; + const flattened = flattenRootObjectUnion(root); + const described = describeSchema(flattened, flattened, describeProperty); + return isObject(described) ? described : flattened; }; diff --git a/src/contracts/toolInputReferences.test.ts b/src/contracts/toolInputReferences.test.ts index 5a2285f20..4441ba9f7 100644 --- a/src/contracts/toolInputReferences.test.ts +++ b/src/contracts/toolInputReferences.test.ts @@ -149,52 +149,78 @@ describe("root input presentation", () => { { anyOf: [branch, branch] }, (property) => `Parameter ${property}`, ); - const branches = z - .array(z.record(z.string(), z.unknown())) - .parse(presented.anyOf); - expect(branches).toHaveLength(2); - for (const presentedBranch of branches) { - expect(presentedBranch).toMatchObject(branch); - const properties = presentedBranch.properties; - if (typeof properties !== "object" || properties === null) - throw new Error("Missing branch properties"); - expect(Object.getPrototypeOf(properties)).toBe(Object.prototype); - expect(Object.hasOwn(properties, "__proto__")).toBe(true); - } + expect(presented).not.toHaveProperty("anyOf"); + expect(presented).toMatchObject({ + type: "object", + required: ["__proto__"], + additionalProperties: false, + }); + const properties = presented.properties; + if (typeof properties !== "object" || properties === null) + throw new Error("Missing root properties"); + expect(Object.getPrototypeOf(properties)).toBe(Object.prototype); + expect(Object.hasOwn(properties, "__proto__")).toBe(true); }); - it("preserves root alternatives, required pairs, and mixed-family exclusions", () => { - const schema = z.union([ - z.strictObject({ before: z.string(), after: z.string() }), - z.strictObject({ - before_scenario: z.number(), - after_scenario: z.number(), - }), - ]); - const canonical = z.toJSONSchema(schema, { io: "input" }); - const advertised = presentInputJsonSchema( - canonical, - (property) => property, - ); - const validate = new Ajv2020({ strict: false }).compile(advertised); - for (const input of [ - {}, - { before: "first" }, - { before: "first", after: "second" }, - { before_scenario: 1, after_scenario: 2 }, - { before: "first", after_scenario: 2 }, - { + it.each(["draft-2020-12", "draft-07"] as const)( + "advertises complete root groups while runtime keeps the exact union in %s", + (target) => { + const schema = z.union([ + z.strictObject({ before: z.string(), after: z.string() }), + z.strictObject({ + before_scenario: z.number(), + after_scenario: z.number(), + normalization: z.boolean().optional(), + }), + ]); + const canonical = z.toJSONSchema(schema, { io: "input", target }); + const advertised = presentInputJsonSchema( + canonical, + (property) => property, + ); + // Anthropic tool input schemas reject anyOf, oneOf, and allOf at the root. + for (const combinator of ["anyOf", "oneOf", "allOf"]) + expect(advertised).not.toHaveProperty(combinator); + expect(advertised.description).toBe( + "Provide a complete input group: before + after; before_scenario + after_scenario + [normalization].", + ); + const ajv = + target === "draft-2020-12" + ? new Ajv2020({ strict: false }) + : new Ajv({ strict: false }); + const validate = ajv.compile(advertised); + for (const input of [ + { before: "first", after: "second" }, + { before_scenario: 1, after_scenario: 2 }, + { before_scenario: 1, after_scenario: 2, normalization: true }, + ]) { + expect(schema.safeParse(input).success).toBe(true); + expect(validate(input)).toBe(true); + } + for (const input of [ + {}, + { before: "first" }, + { unexpected: true }, + { before_scenario: 1, after_scenario: "wrong" }, + { before_scenario: 1, normalization: true }, + { after_scenario: 2, normalization: true }, + ]) { + expect(schema.safeParse(input).success).toBe(false); + expect(validate(input)).toBe(false); + } + // Cross-group exclusion is enforced only by the canonical runtime parser. + const mixed = { before: "first", after: "second", before_scenario: 1, after_scenario: 2, - }, - { before_scenario: 1, after_scenario: "wrong" }, - ]) - expect(validate(input)).toBe(schema.safeParse(input).success); - }); + }; + expect(validate(mixed)).toBe(true); + expect(schema.safeParse(mixed).success).toBe(false); + }, + ); - it("retains reference siblings and does not manufacture root branch constraints", () => { + it("keeps a root branch whose reference siblings cannot be merged", () => { const branch = { $ref: "#/$defs/object", additionalProperties: false }; const root = { $defs: { @@ -205,7 +231,7 @@ describe("root input presentation", () => { const presented = presentInputJsonSchema(root, (property) => property); expect(presented.anyOf).toEqual([branch]); const ajv = new Ajv2020({ strict: false }); - for (const sample of [{}, { value: "value" }, null]) + for (const sample of [{}, { value: "value" }, { other: 1 }, null]) expect(ajv.compile(presented)(sample)).toBe(ajv.compile(root)(sample)); }); diff --git a/tests/boundary/mcp/browserComparisonInput.test.ts b/tests/boundary/mcp/browserComparisonInput.test.ts index 66104d292..9d6cdc5f9 100644 --- a/tests/boundary/mcp/browserComparisonInput.test.ts +++ b/tests/boundary/mcp/browserComparisonInput.test.ts @@ -23,6 +23,38 @@ const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE); const contract = toolContract("compare_web_captures"); +async function capturePassivePair( + provider: CdpBrowserProvider, + browser: Awaited>, +) { + const produced = await provider.inspectPage( + inspectWebPageInputSchema.parse({ + cdp_endpoint: browser.endpoint, + target_id: "allowed-page", + allowed_origins: [browser.allowedOrigin, "https://private.example.test"], + observation_ms: 0, + include_json_body_shapes: true, + include_websocket_shapes: true, + }), + ); + if (!produced.ok) throw produced.error; + // Capture order must not turn identical frame identities into a DOM change. + produced.value.frames = [null, browser.allowedOrigin, ""].map( + (origin, index) => ({ + frame_id: String(index), + parent_frame_id: null, + url: "about:blank", + origin, + }), + ); + const reordered = structuredClone(produced.value); + reordered.frames.reverse(); + return { + before: { inspection: produced.value }, + after: { inspection: reordered }, + }; +} + describe("browser comparison input boundary", () => { it("advertises complete producer captures and agrees with SDK validation on both comparison families", async () => { const browser = await startFakeCdpBrowser({ sensitiveShapes: true }); @@ -51,40 +83,12 @@ describe("browser comparison input boundary", () => { ); if (advertised === undefined) throw new Error("Missing comparison tool"); expect(advertised.inputSchema.type).toBe("object"); - expect(advertised.inputSchema.anyOf).toHaveLength(2); + // Anthropic tool input schemas reject root combinators. + expect(advertised.inputSchema).not.toHaveProperty("anyOf"); const ajv = new Ajv2020({ strict: false, validateFormats: false }); expect(ajv.validateSchema(advertised.inputSchema)).toBe(true); const validate = ajv.compile(advertised.inputSchema); - const produced = await provider.inspectPage( - inspectWebPageInputSchema.parse({ - cdp_endpoint: browser.endpoint, - target_id: "allowed-page", - allowed_origins: [ - browser.allowedOrigin, - "https://private.example.test", - ], - observation_ms: 0, - include_json_body_shapes: true, - include_websocket_shapes: true, - }), - ); - if (!produced.ok) throw produced.error; - // The same frame URL can occur under different origins. Capture order - // must not turn identical frame identities into a DOM change. - produced.value.frames = [null, browser.allowedOrigin, ""].map( - (origin, index) => ({ - frame_id: String(index), - parent_frame_id: null, - url: "about:blank", - origin, - }), - ); - const reordered = structuredClone(produced.value); - reordered.frames.reverse(); - const passive = { - before: { inspection: produced.value }, - after: { inspection: reordered }, - }; + const passive = await capturePassivePair(provider, browser); const scenario = contract.examples[0]?.input; if (scenario === undefined) throw new Error("Missing scenario example"); const withoutNormalization = Object.fromEntries( @@ -99,12 +103,19 @@ describe("browser comparison input boundary", () => { { before: { inspection: {} }, after: passive.after }, { before: passive.before, - after: { inspection: produced.value, webmcp: {} }, + after: { ...passive.after, webmcp: {} }, }, { before_scenario: {}, after_scenario: {} }, { before_scenario: scenario.before_scenario }, - { ...passive, ...scenario }, { ...passive, normalization: { rules: [] } }, + { + before_scenario: scenario.before_scenario, + normalization: { rules: [] }, + }, + { + after_scenario: scenario.after_scenario, + normalization: { rules: [] }, + }, { ...passive, unexpected: true }, { ...scenario, @@ -119,26 +130,39 @@ describe("browser comparison input boundary", () => { }, }, ]; - const cases = [ + // The projection leaves group exclusion to the canonical runtime parser. + const mixedGroups = [{ ...passive, ...scenario }]; + for (const { input, advertisedValid, runtimeValid } of [ ...[passive, scenario, withoutNormalization].map((input) => ({ input, - expected: true, + advertisedValid: true, + runtimeValid: true, })), - ...invalid.map((input) => ({ input, expected: false })), - ]; - for (const { input, expected } of cases) { - expect(validate(input), JSON.stringify(validate.errors)).toBe(expected); + ...invalid.map((input) => ({ + input, + advertisedValid: false, + runtimeValid: false, + })), + ...mixedGroups.map((input) => ({ + input, + advertisedValid: true, + runtimeValid: false, + })), + ]) { + expect(validate(input), JSON.stringify(validate.errors)).toBe( + advertisedValid, + ); expect( browserCaptureComparisonInputSchema.safeParse(input).success, - ).toBe(expected); + ).toBe(runtimeValid); const beforeCalls = calls; const result = await client.callTool({ name: contract.name, arguments: input, }); - expect(calls - beforeCalls).toBe(expected ? 1 : 0); - expect(result.isError === true).toBe(!expected); - if (expected) + expect(calls - beforeCalls).toBe(runtimeValid ? 1 : 0); + expect(result.isError === true).toBe(!runtimeValid); + if (runtimeValid) expect(result.structuredContent).toMatchObject({ operation: contract.name, normalized_result: compareBrowserCaptures( @@ -147,6 +171,10 @@ describe("browser comparison input boundary", () => { }); } const parsedPassive = browserCaptureComparisonInputSchema.parse(passive); + expect(parsedPassive).toEqual({ + before: { ...passive.before, webmcp: null }, + after: { ...passive.after, webmcp: null }, + }); expect(compareBrowserCaptures(parsedPassive)).toMatchObject({ dimensions: { dom_structure: { status: "unchanged" } }, }); diff --git a/tests/boundary/mcp/toolSchemaValidity.test.ts b/tests/boundary/mcp/toolSchemaValidity.test.ts index 7a0fc43ad..1540964fd 100644 --- a/tests/boundary/mcp/toolSchemaValidity.test.ts +++ b/tests/boundary/mcp/toolSchemaValidity.test.ts @@ -396,15 +396,18 @@ describe("MCP root input schemas", () => { expect(ajv.compile(graphTool.inputSchema)({ unrelated: true })).toBe( false, ); + expect(graphTool.inputSchema.description).toContain( + "Provide a complete input group", + ); + expect(graphTool.inputSchema.description).not.toContain("exactly one"); for (const contract of TOOL_CONTRACTS) { const inputSchema = advertised.get(contract.name)!.inputSchema; expect(inputSchema.type, contract.name).toBe("object"); - expect( - inputSchema.properties !== undefined || - Array.isArray(inputSchema.anyOf), - contract.name, - ).toBe(true); + expect(inputSchema.properties, contract.name).toBeDefined(); + // Anthropic tool input schemas reject root combinators. + for (const combinator of ["anyOf", "oneOf", "allOf"]) + expect(inputSchema, contract.name).not.toHaveProperty(combinator); const validate = ajv.compile(inputSchema); for (const example of contract.examples) expect( From 001851fde6f972e6ebd01fddccdff4c645a85f63 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:13:48 +0800 Subject: [PATCH 123/189] fix(javascript): preserve capture-time guards and ordering --- ...manticAnalysis.reference_lifetimes.test.ts | 92 ++++++++++++++++++ .../javascriptSemanticMemberMutations.ts | 12 ++- .../javascriptSemanticMutationInitializers.ts | 94 ++++++++++++++----- .../javascript/javascriptSemanticValues.ts | 26 +++-- .../applicationWorkflowCli.test.ts | 16 +++- 5 files changed, 203 insertions(+), 37 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts index 01a9566de..0a339f2ca 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts @@ -104,6 +104,98 @@ describe("reference lifetimes across calls and shallow copies", () => { ); }); +describe("capture ordering within declarations and expressions", () => { + it.each([ + "const ignored = mutate(source);", + "void mutate(source);", + "consume(mutate(source));", + ])("preserves a primitive before a later nested call: %s", (escape) => { + expect( + resultValue( + `const source={value:1}; const snapshot=source.value; ${escape} return snapshot;`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const source={value:1}; ${escape} const snapshot=source.value; return snapshot;`, + )?.status, + ).toBe("unknown"); + }); + + it("preserves a primitive before an awaited escape", () => { + const value = onlyCallable( + analyzeJavaScriptSemantics(`export async function result() { + const source={value:1}; const snapshot=source.value; + await mutate(source); return snapshot; + }`), + "result", + ).returnSites[0]?.value; + expect(value).toEqual({ status: "literal", value: 1 }); + }); + + it.each([ + "({value:1} as {value:number})", + "({value:1} satisfies {value:number})", + "({value:1})!", + ])("classifies transparent initializer wrappers: %s", (source) => { + expect( + resultValue( + `const source=${source}; const snapshot=source.value; mutate(source); return snapshot;`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const source=${source}; mutate(source); const snapshot=source.value; return snapshot;`, + )?.status, + ).toBe("unknown"); + }); + + it.each(["(source as {value:number})", "(source satisfies {value:number})"])( + "captures through a wrapped alias: %s", + (alias) => { + expect( + resultValue( + `const source={value:1}; const alias=${alias}; const snapshot=alias.value; mutate(alias); return snapshot;`, + ), + ).toEqual({ status: "literal", value: 1 }); + }, + ); + + it.each([ + ["{child:{}}", "{child:copy=fallback}"], + ["[{}]", "[copy=fallback]"], + ])("guards fallback selection before escape: %s", (source, pattern) => { + expect( + resultValue( + `const fallback={value:1}; const source=${source}; const ${pattern}=source; mutate(copy); return fallback.value;`, + ), + ).toEqual({ status: "literal", value: 1 }); + expect( + resultValue( + `const fallback={value:1}; const source=${source}; mutate(source); const ${pattern}=source; mutate(copy); return fallback.value;`, + )?.status, + ).toBe("unknown"); + }); + + it.each([ + "const source={value:1}, snapshot=source.value; mutate(source);", + "const source={value:1}, snapshot=source.value, ignored=mutate(source);", + ])("preserves sequential declarator captures: %s", (body) => { + expect(resultValue(`${body} return snapshot;`)).toEqual({ + status: "literal", + value: 1, + }); + }); + + it("retains an escape in an earlier declarator", () => { + expect( + resultValue( + "const source={value:1}, ignored=mutate(source), snapshot=source.value; return snapshot;", + )?.status, + ).toBe("unknown"); + }); +}); + describe("primitive snapshots across calls", () => { it.each([ "const [copy] = source;", diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 526e937ad..ae887b9c7 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -439,10 +439,13 @@ const referenceSourcesInactive = ( state: JavaScriptSemanticAnalysisState, ): boolean => reference.requiredSources?.some( - (source) => selectedReferenceSlot(source, state)?.presence === "absent", + (source) => + selectedReferenceSlot(source, state, source.node)?.presence === "absent", ) === true || reference.fallbackSources?.some((source) => { - const slot = selectedReferenceSlot(source, state); + // Selection precedes effects through the chosen reference. A later escape + // cannot make a fallback that was excluded at destructuring reachable. + const slot = selectedReferenceSlot(source, state, source.node); return ( slot?.presence === "present" && (slot.value.status === "literal" || @@ -558,7 +561,7 @@ const objectReferencedValues = ( path: [ typeof selected === "object" ? { - ...(selected ?? {}), + ...selected, excludedKeys: [ ...new Set([ ...(selected?.excludedKeys ?? []), @@ -693,6 +696,7 @@ const copiedReferencePath = ( const selectedReferenceSlot = ( source: { readonly node: t.Node; readonly projection: PropertyPath }, state: JavaScriptSemanticAnalysisState, + capturePoint?: t.Node, ) => { const path: string[] = []; for (const key of source.projection) { @@ -700,7 +704,7 @@ const selectedReferenceSlot = ( path.push(String(key)); } return semanticSlotAtPath( - evaluateSemanticExpression(source.node, state), + evaluateSemanticExpression(source.node, state, capturePoint), path, ); }; diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index d80d6b9ad..970f6b1f2 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,23 +1,47 @@ import * as t from "@babel/types"; -import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; +import { + semanticStaticPropertyKey, + unwrapJavaScriptExpression, +} from "./javascriptAstValues.js"; import type { JavaScriptSemanticBindingState } from "./javascriptSemanticState.js"; interface StatementPosition { readonly body: readonly t.Statement[]; readonly index: number; + readonly declaratorIndex: number; } const statementPosition = ( statement: t.Statement, parents: WeakMap, + declarator?: t.VariableDeclarator, ): StatementPosition | null => { const parent = parents.get(statement); if (!t.isProgram(parent) && !t.isBlockStatement(parent)) return null; const index = parent.body.indexOf(statement); - return index < 0 ? null : { body: parent.body, index }; + return index < 0 + ? null + : { + body: parent.body, + index, + declaratorIndex: + t.isVariableDeclaration(statement) && declarator !== undefined + ? statement.declarations.indexOf(declarator) + : -1, + }; }; +const positionPrecedes = ( + left: StatementPosition, + right: StatementPosition, +): boolean => + left.body === right.body && + (left.index < right.index || + (left.index === right.index && + left.declaratorIndex >= 0 && + left.declaratorIndex < right.declaratorIndex)); + const directInitializerPosition = ( node: t.Node, parents: WeakMap, @@ -26,7 +50,7 @@ const directInitializerPosition = ( if (t.isVariableDeclarator(parent) && parent.init === node) { const declaration = parents.get(parent); return t.isVariableDeclaration(declaration) - ? statementPosition(declaration, parents) + ? statementPosition(declaration, parents, parent) : null; } if ( @@ -51,7 +75,7 @@ const directMutationPosition = ( if (t.isVariableDeclarator(node)) { const declaration = parents.get(node); return t.isVariableDeclaration(declaration) - ? statementPosition(declaration, parents) + ? statementPosition(declaration, parents, node) : null; } if (t.isSpreadElement(node)) { @@ -70,10 +94,19 @@ const directMutationPosition = ( !t.isTaggedTemplateExpression(node) ) return null; - const statement = parents.get(node); - return t.isExpressionStatement(statement) && statement.expression === node - ? statementPosition(statement, parents) - : null; + let current = parents.get(node); + while (current !== undefined) { + if (t.isFunction(current)) return null; + if (t.isStatement(current)) return statementPosition(current, parents); + if (t.isVariableDeclarator(current)) { + const declaration = parents.get(current); + return t.isVariableDeclaration(declaration) + ? statementPosition(declaration, parents, current) + : null; + } + current = parents.get(current); + } + return null; }; const referenceInitializerPosition = ( @@ -91,7 +124,7 @@ const referenceInitializerPosition = ( if (t.isVariableDeclarator(parent)) { const declaration = parents.get(parent); return t.isVariableDeclaration(declaration) - ? statementPosition(declaration, parents) + ? statementPosition(declaration, parents, parent) : null; } current = parent; @@ -117,7 +150,11 @@ export const semanticMutationInitializers = ( position: initializer.entryBody === undefined ? directInitializerPosition(initializer.node, parents) - : { body: initializer.entryBody.body, index: -1 }, + : { + body: initializer.entryBody.body, + index: -1, + declaratorIndex: -1, + }, })), ...binding.referenceInitializers.map((initializer) => ({ initializer, @@ -127,19 +164,25 @@ export const semanticMutationInitializers = ( if ( origins.some( ({ position }) => - position === null || - position.body !== mutationPosition.body || - position.index >= mutationPosition.index, + position === null || !positionPrecedes(position, mutationPosition), ) ) return binding; - const latestIndex = origins.reduce( - (latest, { position }) => Math.max(latest, position?.index ?? -1), - -1, + const latest = origins.reduce( + (latest, { position }) => + position !== null && + (latest === null || positionPrecedes(latest, position)) + ? position + : latest, + null, ); const retained = new Set( origins - .filter(({ position }) => position?.index === latestIndex) + .filter( + ({ position }) => + position?.index === latest?.index && + position?.declaratorIndex === latest?.declaratorIndex, + ) .map(({ initializer }) => initializer), ); return { @@ -188,8 +231,7 @@ export const semanticBindingPrecedesCapture = ( return ( sourcePosition !== null && capturePosition !== null && - sourcePosition.body === capturePosition.body && - sourcePosition.index < capturePosition.index + positionPrecedes(sourcePosition, capturePosition) ); }; @@ -209,12 +251,13 @@ export const semanticEscapeFollowsCapture = ( return false; // A literal allocates here. Aliases are evaluated at the same capture point, // so an outer/persistent origin still receives all of its own escape effects. + const origin = unwrapJavaScriptExpression(initializer.node).node; if ( - !t.isObjectExpression(initializer.node) && - !t.isArrayExpression(initializer.node) && - !t.isIdentifier(initializer.node) && - !t.isMemberExpression(initializer.node) && - !t.isOptionalMemberExpression(initializer.node) + !t.isObjectExpression(origin) && + !t.isArrayExpression(origin) && + !t.isIdentifier(origin) && + !t.isMemberExpression(origin) && + !t.isOptionalMemberExpression(origin) ) return false; const capturePosition = semanticCapturePosition(capture, parents); @@ -222,7 +265,6 @@ export const semanticEscapeFollowsCapture = ( return ( capturePosition !== null && escapePosition !== null && - capturePosition.body === escapePosition.body && - capturePosition.index < escapePosition.index + positionPrecedes(capturePosition, escapePosition) ); }; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 51dd8da71..2f5362670 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -114,17 +114,25 @@ export const evaluateSemanticBinding = ( primitiveBindingValues: primitiveBindingValuesFor(state), }); -/** Evaluate one arbitrary inert expression in the established lexical state. */ +/** Evaluate an inert expression, optionally at an earlier reference capture. */ export const evaluateSemanticExpression = ( node: t.Node, state: JavaScriptSemanticAnalysisState, -): JavaScriptSemanticValue => - evaluateExpression(node, { + capturePoint?: t.Node, +): JavaScriptSemanticValue => { + const context: EvaluationContext = { state, bindings: new Set(), expressionDepth: 0, primitiveBindingValues: primitiveBindingValuesFor(state), - }); + }; + return evaluateExpression( + node, + capturePoint === undefined + ? context + : (captureContextAt(capturePoint, context) ?? context), + ); +}; /** Follow module provenance through destructuring, members, and aliases. */ export const evaluateSemanticProvenance = ( @@ -733,11 +741,17 @@ const isPrimitive = (value: JavaScriptSemanticValue): boolean => const primitiveCaptureContext = ( node: t.Node, context: EvaluationContext, +): EvaluationContext | undefined => { + if (t.isObjectExpression(node) || t.isArrayExpression(node)) return undefined; + return captureContextAt(node, context); +}; + +const captureContextAt = ( + node: t.Node, + context: EvaluationContext, ): EvaluationContext | undefined => { if ( context.capturePoint !== undefined || - t.isObjectExpression(node) || - t.isArrayExpression(node) || semanticCapturePosition(node, context.state.parentsByNode) === null ) return undefined; diff --git a/tests/acceptance/applications/applicationWorkflowCli.test.ts b/tests/acceptance/applications/applicationWorkflowCli.test.ts index 9abbd4f0d..a16378317 100644 --- a/tests/acceptance/applications/applicationWorkflowCli.test.ts +++ b/tests/acceptance/applications/applicationWorkflowCli.test.ts @@ -541,6 +541,9 @@ describe("application workflow CLI and MCP capture lifetimes", () => { "destructured", "objectSnapshot", "arraySnapshot", + "unusedFallback", + "nestedSnapshot", + "declaratorSnapshot", ]; const sources = [ `export default function make() { @@ -559,11 +562,22 @@ describe("application workflow CLI and MCP capture lifetimes", () => { const objectSnapshot = {value: source.value}; const arraySnapshot = [source.value]; mutate(source); + const fallback = {value: "TOKEN"}; + const container = {child: {}}; + const {child: selected = fallback} = container; + mutate(selected); + const nestedSource = {value: "TOKEN"}; + const nestedSnapshot = nestedSource.value; + const ignored = mutate(nestedSource); + const declaratorSource = {value: "TOKEN"}, + declaratorSnapshot = declaratorSource.value, + declaratorIgnored = mutate(declaratorSource); return { kind: "capture-boundary", rebound: original.value, rest: child.value, snapshot, destructured, objectSnapshot: objectSnapshot.value, arraySnapshot: arraySnapshot[0], + unusedFallback: fallback.value, nestedSnapshot, declaratorSnapshot, }; }`, `export default function make() { return ${JSON.stringify({ @@ -597,7 +611,7 @@ describe("application workflow CLI and MCP capture lifetimes", () => { await writeFile(inputPath, JSON.stringify(input)); const expected = { normalized_result: { - summary: { added: 0, removed: 0, changed: 6, unknown: 0 }, + summary: { added: 0, removed: 0, changed: fields.length, unknown: 0 }, coverage: { status: "complete-within-inputs" }, changes: expect.arrayContaining( fields.map((field) => From 08ec2bf82fa88f5e8caa2b7da9093636731dc55c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:14:55 +0800 Subject: [PATCH 124/189] chore(main): release rea-agents 6.3.0 (#1341) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 158 ++++++++++++++++++++++++++++++++ docs/installation.md | 2 +- package-lock.json | 4 +- package.json | 2 +- server.json | 4 +- src/generatedPackageMetadata.ts | 2 +- 7 files changed, 166 insertions(+), 8 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e1e352c16..5c753b441 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "6.2.0" + ".": "6.3.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd5ae5cd..067d699ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,163 @@ # Changelog +## [6.3.0](https://github.com/morluto/rea/compare/rea-agents-6.2.0...rea-agents-6.3.0) (2026-10-09) + + +### ⚠ BREAKING CHANGES + +* **browser:** JSON shape paths now contain typed property and array-element segments. WebMCP input_schema_shape is replaced by input_schema and input_schema_sha256, retaining declared examples and defaults. +* **process:** Filesystem digest omission entries now require system_code; budget and changed-file omissions use null, and unavailable-file omissions preserve the operating-system error code. +* **contracts:** Provider analysis outputs must explicitly supply metadata previously repaired with defaults; unsupported nullable facets must be reported as null. +* **javascript:** Semantic graph facts now store evidence context IDs and locations. Graph and semantic trace results require an inline evidence_contexts table. +* **contracts:** source-map URLs now live in target observations selected by declared_url_sha256, and doctor skill identity no longer emits installed_catalog_digest. Use the documented observation join and identity.skill.state instead. +* **javascript:** remove the never-incremented truncated_scopes statistic from JavaScript application analysis results and schemas. +* **native:** Objective-C attribute tokens now contain only name and value. Properties report nullable atomicity and readonly facts; class flags, ivar counts, and method requirement flags are nullable when unobserved. + +### Features + +* **javascript:** record Electron integrity mismatches ([7915ee5](https://github.com/morluto/rea/commit/7915ee51781878ed67e094259924b6e6f3093b3f)) + + +### Bug Fixes + +* **artifacts:** bind ASAR interpretation to owned snapshots ([d79317c](https://github.com/morluto/rea/commit/d79317cda0bbe8240eb7e25b0a5de90dcffca5fa)) +* **artifacts:** infer legacy Mach-O simulator platforms ([5aa2002](https://github.com/morluto/rea/commit/5aa200285ab066e48b37b716495936e6e2a963fd)) +* **artifacts:** preserve archive facts and Unicode path identity ([5751f5c](https://github.com/morluto/rea/commit/5751f5caac86c770123ae739a4e4101a72b0989c)) +* **artifacts:** reject incomplete inventoried extraction ([5e8fb53](https://github.com/morluto/rea/commit/5e8fb531e255a4a04fc053c54096f66d5c84cde3)) +* **artifacts:** retain DMG ownership through uncertain attachment ([a27794c](https://github.com/morluto/rea/commit/a27794c246b3f11d7f92ae7f6d276718190ab731)) +* **artifacts:** validate only active extraction entries ([cfb12e4](https://github.com/morluto/rea/commit/cfb12e47dc241f057be93a00892f7d7361d6119d)) +* **browser:** follow only HTTP redirect statuses for source maps ([82bbe74](https://github.com/morluto/rea/commit/82bbe743336244d398e67512659ea6943d43a4a4)) +* **browser:** preserve payload shapes and WebMCP declarations ([4951a89](https://github.com/morluto/rea/commit/4951a897c53bb6882300c5d7a9660a3f43e374f5)) +* **browser:** release attached viewport overrides without resizing the external page ([f6cfbfc](https://github.com/morluto/rea/commit/f6cfbfcc554ff24173dd7ad5333e8e26ab9c962d)) +* **browser:** retain attached scenario emulation until cleanup ([a0523b3](https://github.com/morluto/rea/commit/a0523b375eb3147f1d2d1e7eb10a2f4546f5d0fc)) +* **browser:** retain malformed redirect diagnostics ([617cd84](https://github.com/morluto/rea/commit/617cd84d27d100e7cc3cd4b5721dea4a996c9775)) +* **browser:** serialize attached scenarios through cleanup settlement ([cfce91d](https://github.com/morluto/rea/commit/cfce91d418fbcde4a9ef283a61549279751854e7)) +* **ci:** scope verification and reuse native runners ([#1344](https://github.com/morluto/rea/issues/1344)) ([d5cb8ae](https://github.com/morluto/rea/commit/d5cb8aee063065a48233458e04771635167825c8)) +* **cli:** avoid duplicate primary cleanup diagnostics ([37fcea7](https://github.com/morluto/rea/commit/37fcea78cecbeeadd869e9a3d77dd133ed264a0a)) +* **cli:** classify JSON input permission denials ([08daf05](https://github.com/morluto/rea/commit/08daf056cc8e4d092f9592574d09d5182457b7bc)) +* **cli:** classify oversized JSON inputs ([f7cf4c8](https://github.com/morluto/rea/commit/f7cf4c890d4b9c70b1f56e6c627b44a59e58fd73)) +* **cli:** stream JSON inputs beyond the whole-document string limit ([#1360](https://github.com/morluto/rea/issues/1360)) ([6ce3288](https://github.com/morluto/rea/commit/6ce3288f3bd65a886e47905455ed5c9b661015e6)), closes [#1331](https://github.com/morluto/rea/issues/1331) +* **cli:** stream JSON results at the shared command boundary ([810107a](https://github.com/morluto/rea/commit/810107a2ad15cc52afd6662aec24d231d8c77225)) +* **contracts:** advertise NUL with a portable hex escape ([3f59a84](https://github.com/morluto/rea/commit/3f59a84bd1039763bb349894542601ed78be2033)), closes [#1329](https://github.com/morluto/rea/issues/1329) +* **contracts:** require observed provider output metadata ([a4ba8ae](https://github.com/morluto/rea/commit/a4ba8aecd507637b6261026afc17f79516840d50)) +* **electron:** preserve unrepresentable numeric option evidence ([41a228c](https://github.com/morluto/rea/commit/41a228c1b01a89127858b1706879ede08a81deaf)) +* **evidence:** order canonical projections independently of locale ([614fb76](https://github.com/morluto/rea/commit/614fb7681ee9e4eba7219c1ee9e90d6a85d78095)) +* **files:** reject nonregular capture and JSON inputs ([5f16124](https://github.com/morluto/rea/commit/5f16124a31fa4a82bd03037506809d6be959d768)) +* **filesystem:** reject unstable artifact targets ([7829b1a](https://github.com/morluto/rea/commit/7829b1aeef8f43f186be2d2adbd6c67541306a7a)) +* **ghidra:** reject a native decompiler built for another host ([#1280](https://github.com/morluto/rea/issues/1280)) ([3728c82](https://github.com/morluto/rea/commit/3728c8267b4fb6da78cbae42a2a6cbddff80ea84)), closes [#1192](https://github.com/morluto/rea/issues/1192) +* **ghidra:** retain process ownership after failed launch rollback ([07675f7](https://github.com/morluto/rea/commit/07675f78c66ce9e8706e808d417265e18ba9f3a5)) +* **ghidra:** verify dense jump tables on an optimized fixture ([#1374](https://github.com/morluto/rea/issues/1374)) ([73a664b](https://github.com/morluto/rea/commit/73a664bc78ee618045a2733b8714821281f77403)) +* **hopper:** allow restart after verified owned-provider shutdown ([1c12349](https://github.com/morluto/rea/commit/1c123493a21cc579ba7532c40e7ef30df45db3e8)) +* **hopper:** probe interior navigation from multi-byte instructions ([#1285](https://github.com/morluto/rea/issues/1285)) ([bf934d5](https://github.com/morluto/rea/commit/bf934d5592e707ba5e7769043de3a430ed8d4923)) +* **ida:** compare admitted document paths consistently ([890bb66](https://github.com/morluto/rea/commit/890bb66b35d5f9f8ee54ff0049bf7dc7b82b2480)) +* **javascript:** avoid positive-zero evidence for signed zero ([9055bd6](https://github.com/morluto/rea/commit/9055bd695b75f72fb1b8a538d1485d30c0b0ee0b)) +* **javascript:** decline source-map UNC references with an unusable host ([#1372](https://github.com/morluto/rea/issues/1372)) ([f504c2a](https://github.com/morluto/rea/commit/f504c2a351027f17ac353fba2d7cfc3505ee17d6)) +* **javascript:** distinguish prefix-only builtins from packages ([2b4abbf](https://github.com/morluto/rea/commit/2b4abbf1ccb6dd6ad1248cf48e381df0842542c1)) +* **javascript:** honor module-sync package exports ([#1361](https://github.com/morluto/rea/issues/1361)) ([d0e6069](https://github.com/morluto/rea/commit/d0e606930acb701790c286340226b1e3e7060b4f)) +* **javascript:** parse declaration artifacts in ambient mode ([4896adc](https://github.com/morluto/rea/commit/4896adcd0f9316034e83129685ed3807ade6f3ea)) +* **javascript:** preserve agreeing module provenance ([db171be](https://github.com/morluto/rea/commit/db171be6e570fd1261a30d711e4da2d17de85a93)) +* **javascript:** preserve capture-time guards and ordering ([001851f](https://github.com/morluto/rea/commit/001851fde6f972e6ebd01fddccdff4c645a85f63)) +* **javascript:** preserve semantic evidence through satisfies ([e995b19](https://github.com/morluto/rea/commit/e995b19f834ba78faa294f5959fd3ad8a97290ca)) +* **javascript:** preserve uncertainty after references escape to calls ([#1292](https://github.com/morluto/rea/issues/1292)) ([355a292](https://github.com/morluto/rea/commit/355a292198bf58245c67ae315fdb4f77e62769cc)) +* **javascript:** reject invalid package exports configurations ([7a4f268](https://github.com/morluto/rea/commit/7a4f2685d41b134507331c322f0f5da8e1f6c3f4)) +* **javascript:** resolve exported callables through lexical bindings ([#1351](https://github.com/morluto/rea/issues/1351)) ([a9f5dad](https://github.com/morluto/rea/commit/a9f5dad5a8f196c88f6305d8d958b355cc0b52c2)) +* **javascript:** resolve query-only HTML references to their document ([55a46f7](https://github.com/morluto/rea/commit/55a46f7c7176075c9edda4fe61ed995f2ceadf6a)) +* **javascript:** retain array identity after length mutations ([4bcea1a](https://github.com/morluto/rea/commit/4bcea1aa76e3e7ca665197181739c5e27a62c40a)) +* **javascript:** retain distinct module provenance path components ([2bd7de6](https://github.com/morluto/rea/commit/2bd7de6f8ca62fc1d48334cfa7fdced461b7b153)) +* **javascript:** retain unresolved value frontiers in provenance queries ([3e19875](https://github.com/morluto/rea/commit/3e19875c7fa9c61cff655bbe6046ddc4ab558533)) +* **javascript:** store source map URLs once ([ed8fcae](https://github.com/morluto/rea/commit/ed8fcae94b699b62b44162f880faa077a36c455d)) +* **json:** preserve runtime limits across JSON file readers ([#1350](https://github.com/morluto/rea/issues/1350)) ([9c4a68b](https://github.com/morluto/rea/commit/9c4a68bc19a0f7d39557e3cc039f5877f6550f63)) +* **managed:** bind graph facts to their source Evidence ([cc7b5af](https://github.com/morluto/rea/commit/cc7b5af0777fc68ebba10ec061244729ebf2357d)) +* **mcp:** admit composed analysis through result bookkeeping ([e11f4d3](https://github.com/morluto/rea/commit/e11f4d371abaa8cb65ebf7b94fa216329fd78d88)) +* **mcp:** advertise object roots for union input schemas ([#1373](https://github.com/morluto/rea/issues/1373)) ([39dabd0](https://github.com/morluto/rea/commit/39dabd0608ed9617d60f16ece05993089f24ff38)) +* **mcp:** advertise primitive semantic literal seeds ([f62b449](https://github.com/morluto/rea/commit/f62b44971deee0e99df6fcf32758c8e5592400ed)) +* **mcp:** preserve JavaScript workflow identity validation ([#1366](https://github.com/morluto/rea/issues/1366)) ([53ed942](https://github.com/morluto/rea/commit/53ed942a85f51ff9f0e4f01cbb53359df476071d)), closes [#1364](https://github.com/morluto/rea/issues/1364) [#1065](https://github.com/morluto/rea/issues/1065) +* **mcp:** retry failed shutdown resources and retain failure reasons ([e64678e](https://github.com/morluto/rea/commit/e64678e8f9768dd819d8f5f12cc844a6660ff2c5)) +* **native:** distinguish symbol definitions from metadata ([70bad53](https://github.com/morluto/rea/commit/70bad53847b0e14489acee73d204ff645e1adfcd)) +* **native:** preserve unknown Objective-C metadata ([b112d44](https://github.com/morluto/rea/commit/b112d44a3961939881779c81a57e7a3f9d1372f7)) +* **native:** refuse to list architectures of non-Mach-O targets ([#1325](https://github.com/morluto/rea/issues/1325)) ([1b73b5a](https://github.com/morluto/rea/commit/1b73b5ab4bc75bd424e643de8e49f142ffa2b336)) +* **native:** retain LLDB cleanup ownership through client close ([7ad353f](https://github.com/morluto/rea/commit/7ad353fa8b3f07e14face80336678d23cc7c6507)) +* **process:** keep unobserved file contents unknown ([#1358](https://github.com/morluto/rea/issues/1358)) ([f91f279](https://github.com/morluto/rea/commit/f91f2798b4dc6adb61b3ffe28a24a5d55adbd6ff)) +* **process:** retain per-file digest open failures ([415145d](https://github.com/morluto/rea/commit/415145d04f09a15cbfb7dda8ea9dc363a77f9bf0)) +* **reference:** report malformed UTF-8 before import parsing ([f166a2a](https://github.com/morluto/rea/commit/f166a2ae15b072216173a51a8f5cad930a858366)) +* report malformed application evidence as input errors ([218c131](https://github.com/morluto/rea/commit/218c13160ec0ed7116d6633fc76559ec39dae4d7)) +* retain completed observations when later analysis steps fail ([35f121f](https://github.com/morluto/rea/commit/35f121f4acac821e848c485fb82a2c42f51f6ea1)) +* **setup:** install the skill for Claude Code ([b4a1919](https://github.com/morluto/rea/commit/b4a19193fe3baf9075f8ac419517021ea0c71ea3)) +* **setup:** recognize supported Nobara hosts ([f0dc233](https://github.com/morluto/rea/commit/f0dc233d64de4c215c453c346e516b7622713e95)) +* **skill:** pin packaged commands to the shipping package version ([2793672](https://github.com/morluto/rea/commit/2793672ee2a575f97a8011c7fec5288098cdd5d1)) +* **skill:** pin packaged commands to the shipping package version ([#1346](https://github.com/morluto/rea/issues/1346)) ([f39e71c](https://github.com/morluto/rea/commit/f39e71ce1897bb5c704b33a8b0049567f11e3a13)) +* **snapshot:** preserve complete investigation revision histories ([#1354](https://github.com/morluto/rea/issues/1354)) ([1c0cc8a](https://github.com/morluto/rea/commit/1c0cc8a6753b5ac781b28ebb1832f3a6a1771a68)) +* **targets:** cancel resolution before provider admission ([f3c4a33](https://github.com/morluto/rea/commit/f3c4a332f7bd198bd67f0187bc2a85c7b31bb960)) +* **update:** preserve disabled client registrations ([abf5e24](https://github.com/morluto/rea/commit/abf5e243c4d2cae03404b6e1fb1ccc77be917b53)) + + +### Performance Improvements + +* **javascript:** index version relationships once per comparison ([#1347](https://github.com/morluto/rea/issues/1347)) ([b1e85ad](https://github.com/morluto/rea/commit/b1e85ad711743a594c572dbd5b0d5cb664e2a502)) +* **javascript:** validate the version change graph once ([#1370](https://github.com/morluto/rea/issues/1370)) ([037709a](https://github.com/morluto/rea/commit/037709a52c0824f4d2bbee90d8e2642b2d88d364)) +* **json:** encode streamed JSON iteratively ([#1322](https://github.com/morluto/rea/issues/1322)) ([56598be](https://github.com/morluto/rea/commit/56598beb4e82968a313deb9efdf4b98db5bd1f4f)) + + +### Code Refactoring + +* **artifacts:** remove unused root classifier ([5291bca](https://github.com/morluto/rea/commit/5291bca108af781214572fac709f9808bb8aa4db)) +* **artifacts:** test inventory changes at materialization boundary ([750fb65](https://github.com/morluto/rea/commit/750fb6565052e9eaad40b946b6a284d0730d14f8)) +* **browser:** open scenario sessions without a factory wrapper ([d1983a4](https://github.com/morluto/rea/commit/d1983a45767bfcdc020652f48109a78a3f9fa590)) +* **catalog:** import CLI metadata from its owner ([8c96baa](https://github.com/morluto/rea/commit/8c96baab80dc258d31ca1632d761fffb11dbaaae)) +* consolidate boundary semantics and prune redundant tests ([392f1f3](https://github.com/morluto/rea/commit/392f1f310733f2c365da7bc57a1154cf10ec4ba0)) +* **javascript:** normalize erased expression syntax once ([b628bba](https://github.com/morluto/rea/commit/b628bba1fa65fd3b51363bf4b745f0afc57e1dba)) +* **javascript:** parse runtime evidence into one verified owner ([006b295](https://github.com/morluto/rea/commit/006b295f1de19fd5351832cf52d98a202a5cd5cd)) +* **javascript:** remove obsolete scope truncation statistic ([449d570](https://github.com/morluto/rea/commit/449d57075eec71b2f064af8877c50cbbde30a283)) +* **javascript:** share Babel child traversal ([0f10499](https://github.com/morluto/rea/commit/0f10499245ec2fab8823f116caf34450b3a7385b)) +* **javascript:** share semantic evidence at fact construction ([e3bbb9a](https://github.com/morluto/rea/commit/e3bbb9ac453da8d15f3b32511180451613710616)) +* **process:** remove duplicate observation and trace entry points ([070339a](https://github.com/morluto/rea/commit/070339af50a50a0f23e82db859e761c53277ee79)) +* **providers:** use canonical artifact and managed identities ([87f0051](https://github.com/morluto/rea/commit/87f0051496aff1b05ab24d6b63f79884f4ca9b8f)) +* **reference:** simplify malformed UTF-8 handling ([377df71](https://github.com/morluto/rea/commit/377df715ea5b2523cd6c1084fdc286eb8a056182)) +* remove obsolete source exclusions and identity wrapper ([44c92f8](https://github.com/morluto/rea/commit/44c92f88c51841735741811a68cc89fde14efa80)) +* remove single-use forwarding helpers ([4144e45](https://github.com/morluto/rea/commit/4144e454f385c372d29e301e6bb959092c606a6e)) + + +### Documentation + +* add repository-local REA tool design skill ([7738c1f](https://github.com/morluto/rea/commit/7738c1f6a9ccf1ec9868ef832f154abe9ba5eebd)) +* celebrate 40,000 GitHub stars 🎉 ([3edb217](https://github.com/morluto/rea/commit/3edb2172def0e0bd9076f23148f0c41cd2f341a3)) +* celebrate 40,000 GitHub stars 🎉 ([5ecc98a](https://github.com/morluto/rea/commit/5ecc98a5eac4c10d33e9c418b9ffae61c68e3ef2)) +* consolidate agent guidance around ownership and boundaries ([ba44222](https://github.com/morluto/rea/commit/ba4422296dc409d49836f25642555e00463bfe3b)) +* **contracts:** explain canonical URL and skill metadata ownership ([e36afa1](https://github.com/morluto/rea/commit/e36afa112fd7b7ab5a925ca452de93b68f12a6ab)) +* correct MCP error and capture import guidance ([077d6c4](https://github.com/morluto/rea/commit/077d6c407b3ea7443a7277ae0e5531b3927dd742)) +* correct README setup and runtime guidance ([5b3715e](https://github.com/morluto/rea/commit/5b3715ef825a30150b02d3f1bb7d40dd89453018)) +* explain CI scope and native runner reuse ([#1348](https://github.com/morluto/rea/issues/1348)) ([6c9161d](https://github.com/morluto/rea/commit/6c9161d61745e242643f224ce49e7468143a15f3)) +* prune repeated contributor and tool design instructions ([5d79387](https://github.com/morluto/rea/commit/5d79387505ebae1ec8d800ee3ffd901920a9d8be)) +* remove retired architecture and migration artifacts ([7a0c800](https://github.com/morluto/rea/commit/7a0c80085128e6329ca2e4f54f3539f3245c57d1)) + + +### Tests + +* **android:** allow provider readiness under load ([961c3c3](https://github.com/morluto/rea/commit/961c3c3de79ec44d608d011eb3fa3d6bd645cf6a)) +* **artifacts:** verify extraction races with real filesystem changes ([1ac8389](https://github.com/morluto/rea/commit/1ac8389c5c1f75faf8d7f2f3faf2f24febad5fea)) +* **browser:** avoid duplicating source-map listener setup ([9367dc1](https://github.com/morluto/rea/commit/9367dc13bd8d2732d36d5376b5de170c9f4af424)) +* **browser:** report redirect status cases independently ([5a61562](https://github.com/morluto/rea/commit/5a61562dc200120c7b8020854085c17b8203e95d)) +* **cli:** remove duplicate malformed JSON assertion ([5d32e42](https://github.com/morluto/rea/commit/5d32e4252941e93065cadd83b9f02aa6427544d8)) +* exercise source test selection through Git and Vitest ([25711ad](https://github.com/morluto/rea/commit/25711ad2590af136dfb301839dddd6d30971ba76)) +* **filesystem:** bound FIFO regressions at consumers ([0bfb6e0](https://github.com/morluto/rea/commit/0bfb6e00abae1e67a96e548d64954bb21861f621)) +* **ghidra:** allow rollback tests to reach spawned process ([d761d73](https://github.com/morluto/rea/commit/d761d7358b45fe0724b182a206241fd605f338b0)) +* **javascript:** share primitive expansion producer fixtures ([c867bcd](https://github.com/morluto/rea/commit/c867bcd0aadd63473865f9a328459e0db3c89565)) +* **javascript:** share semantic graph test facts ([ac356c4](https://github.com/morluto/rea/commit/ac356c46ad6a17c8864bc5d350984786db62d2f5)) +* **javascript:** verify distinct module origins through reconstruction ([96b2b24](https://github.com/morluto/rea/commit/96b2b245fdefc9c78f5dcf6ce054232b51f7c117)) +* **json:** remove assertions covered by CLI output consumers ([a959a83](https://github.com/morluto/rea/commit/a959a8309db79fbee6477efd7ee541615e625627)) +* **managed:** include shared dossier fixture in artifact inputs ([66a20a2](https://github.com/morluto/rea/commit/66a20a2597b5daebc0a292361aa62a78b7df6e7d)) +* **native:** retain trace diagnostics when observed hits differ ([048b798](https://github.com/morluto/rea/commit/048b79878c70c594789909082499dc675472b63a)) +* **package:** share validated native dossier fixtures ([ca90109](https://github.com/morluto/rea/commit/ca9010936a934a49fbc6cf69eb1d7fc2242b6da9)) +* **process:** publish capture readiness atomically ([74be526](https://github.com/morluto/rea/commit/74be52611e66f680ef1919d521fc3c304bc2326e)) +* **process:** report cleanup details on cancellation failures ([79d5b9a](https://github.com/morluto/rea/commit/79d5b9a826b9204c1ef59b0a5c5ec83e7a2f2bec)) +* **process:** use owned CLI and workspace fixtures ([4940a86](https://github.com/morluto/rea/commit/4940a867e2e56cbb974bfa321008a8f35db47d52)) +* share snapshot replay and managed graph fixtures ([d83cbd2](https://github.com/morluto/rea/commit/d83cbd2abf1bbf15beef990f5353457fdbaaeb8e)) + + +### Continuous Integration + +* enforce architecture guards with portable checkout paths ([ecc67ca](https://github.com/morluto/rea/commit/ecc67cab2d85cacda245890ffe84b80ac395d79e)) + ## [6.2.0](https://github.com/morluto/rea/compare/rea-agents-6.1.0...rea-agents-6.2.0) (2026-10-09) diff --git a/docs/installation.md b/docs/installation.md index c47062a6f..77fc896d5 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -697,7 +697,7 @@ For a client that requires manual configuration, use: "mcpServers": { "rea": { "command": "npx", - "args": ["-y", "rea-agents@6.2.0", "mcp"] + "args": ["-y", "rea-agents@6.3.0", "mcp"] } } } diff --git a/package-lock.json b/package-lock.json index 212d6b8eb..e9bc42c5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "license": "MIT", "dependencies": { "@babel/parser": "8.0.4", diff --git a/package.json b/package.json index 1c41d19bc..69cc9232b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "rea-agents", "mcpName": "io.github.morluto/rea", - "version": "6.2.0", + "version": "6.3.0", "description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.", "license": "MIT", "repository": { diff --git a/server.json b/server.json index 74c21bec1..15253c28c 100644 --- a/server.json +++ b/server.json @@ -8,13 +8,13 @@ "url": "https://github.com/morluto/rea", "source": "github" }, - "version": "6.2.0", + "version": "6.3.0", "packages": [ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "runtimeHint": "npx", "transport": { "type": "stdio" diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index 77fc01683..29177bf02 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -1,7 +1,7 @@ /** Generated from package.json and package-lock.json; do not edit. */ export const PACKAGE_METADATA = { name: "rea-agents", - version: "6.2.0", // x-release-please-version + version: "6.3.0", // x-release-please-version serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", From e10c934d5a756c1a4c7b547ebd02c403ddfde7b8 Mon Sep 17 00:00:00 2001 From: GRAB Racem Date: Sat, 10 Oct 2026 01:36:11 +0200 Subject: [PATCH 125/189] fix(ghidra): keep the cross-format branch callee multi-block The cross-format oracle requires a callee whose recovered control flow has more than one basic block, and rea_cross_branch provided it through a symmetric if/else of tail calls. Clang 21 folds that shape into a conditional negate plus one tail branch, a single basic block, so the lane rejected a correct Ghidra analysis of the fixture. Give the branch a loop whose trip count depends on a volatile global: no compiler can eliminate the backedge, and the callee stays multi-block at every optimization level on every toolchain. --- tests/conformance/ghidra/cross-format.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/conformance/ghidra/cross-format.c b/tests/conformance/ghidra/cross-format.c index f718b9b54..22efa6159 100644 --- a/tests/conformance/ghidra/cross-format.c +++ b/tests/conformance/ghidra/cross-format.c @@ -8,10 +8,15 @@ __attribute__((noinline, used)) int rea_cross_leaf(int value) { } __attribute__((noinline, used)) int rea_cross_branch(int value) { - if (value > 10) { - return rea_cross_leaf(value); + /* A volatile-dependent loop keeps this callee multi-block at every + optimization level: newer clang folds a symmetric if/else of tail calls + into a conditional negate, and cross-format verification requires a + recovered multi-block callee. */ + int adjusted = value > 10 ? value + 1 : -value; + while (adjusted > 100) { + adjusted -= rea_cross_global; } - return rea_cross_leaf(-value); + return rea_cross_leaf(adjusted); } __attribute__((noinline, used)) int rea_cross_indirect( From b8a8190b2f30e377eee2d69d1ba31ea454fa70b9 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:40:25 +0800 Subject: [PATCH 126/189] fix(javascript): retain conditional mutation ordering uncertainty --- ...manticAnalysis.reference_lifetimes.test.ts | 2 ++ .../javascriptSemanticMutationInitializers.ts | 24 ++++++++++++------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts index 0a339f2ca..2795427bd 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts @@ -72,6 +72,8 @@ describe("reference lifetimes across calls and shallow copies", () => { "mutate(alias); alias={};", "if(flag) alias={}; mutate(alias);", "alias={}; if(flag) mutate(alias);", + "alias={}; flag && mutate(alias);", + "alias={}; flag ? mutate(alias) : noop();", "function invoke(){mutate(alias);} alias={}; invoke();", "alias={}; mutate(alias); alias=source;", ])("retains uncertain call ordering: %s", (body) => { diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 970f6b1f2..cfaaf0ef5 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -94,19 +94,25 @@ const directMutationPosition = ( !t.isTaggedTemplateExpression(node) ) return null; - let current = parents.get(node); - while (current !== undefined) { - if (t.isFunction(current)) return null; - if (t.isStatement(current)) return statementPosition(current, parents); - if (t.isVariableDeclarator(current)) { - const declaration = parents.get(current); + let current: t.Node = node; + while (true) { + const parent = parents.get(current); + if ( + parent === undefined || + t.isFunction(parent) || + (t.isLogicalExpression(parent) && parent.right === current) || + (t.isConditionalExpression(parent) && parent.test !== current) + ) + return null; + if (t.isStatement(parent)) return statementPosition(parent, parents); + if (t.isVariableDeclarator(parent)) { + const declaration = parents.get(parent); return t.isVariableDeclaration(declaration) - ? statementPosition(declaration, parents, current) + ? statementPosition(declaration, parents, parent) : null; } - current = parents.get(current); + current = parent; } - return null; }; const referenceInitializerPosition = ( From 565f2efa0337648324db294822103a39ccfab013 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:41:35 +0000 Subject: [PATCH 127/189] chore(release/6.3.0): release rea-agents 6.3.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 159 ++++++++++++++++++++++++++++++++ docs/installation.md | 2 +- package-lock.json | 4 +- package.json | 2 +- server.json | 4 +- src/generatedPackageMetadata.ts | 2 +- 7 files changed, 167 insertions(+), 8 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e1e352c16..5c753b441 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "6.2.0" + ".": "6.3.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd5ae5cd..0ca2fc91d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,164 @@ # Changelog +## [6.3.0](https://github.com/morluto/rea/compare/rea-agents-6.2.0...rea-agents-6.3.0) (2026-10-09) + + +### ⚠ BREAKING CHANGES + +* **browser:** JSON shape paths now contain typed property and array-element segments. WebMCP input_schema_shape is replaced by input_schema and input_schema_sha256, retaining declared examples and defaults. +* **process:** Filesystem digest omission entries now require system_code; budget and changed-file omissions use null, and unavailable-file omissions preserve the operating-system error code. +* **contracts:** Provider analysis outputs must explicitly supply metadata previously repaired with defaults; unsupported nullable facets must be reported as null. +* **javascript:** Semantic graph facts now store evidence context IDs and locations. Graph and semantic trace results require an inline evidence_contexts table. +* **contracts:** source-map URLs now live in target observations selected by declared_url_sha256, and doctor skill identity no longer emits installed_catalog_digest. Use the documented observation join and identity.skill.state instead. +* **javascript:** remove the never-incremented truncated_scopes statistic from JavaScript application analysis results and schemas. +* **native:** Objective-C attribute tokens now contain only name and value. Properties report nullable atomicity and readonly facts; class flags, ivar counts, and method requirement flags are nullable when unobserved. + +### Features + +* **javascript:** record Electron integrity mismatches ([7915ee5](https://github.com/morluto/rea/commit/7915ee51781878ed67e094259924b6e6f3093b3f)) + + +### Bug Fixes + +* **artifacts:** bind ASAR interpretation to owned snapshots ([d79317c](https://github.com/morluto/rea/commit/d79317cda0bbe8240eb7e25b0a5de90dcffca5fa)) +* **artifacts:** infer legacy Mach-O simulator platforms ([5aa2002](https://github.com/morluto/rea/commit/5aa200285ab066e48b37b716495936e6e2a963fd)) +* **artifacts:** preserve archive facts and Unicode path identity ([5751f5c](https://github.com/morluto/rea/commit/5751f5caac86c770123ae739a4e4101a72b0989c)) +* **artifacts:** reject incomplete inventoried extraction ([5e8fb53](https://github.com/morluto/rea/commit/5e8fb531e255a4a04fc053c54096f66d5c84cde3)) +* **artifacts:** retain DMG ownership through uncertain attachment ([a27794c](https://github.com/morluto/rea/commit/a27794c246b3f11d7f92ae7f6d276718190ab731)) +* **artifacts:** validate only active extraction entries ([cfb12e4](https://github.com/morluto/rea/commit/cfb12e47dc241f057be93a00892f7d7361d6119d)) +* **browser:** follow only HTTP redirect statuses for source maps ([82bbe74](https://github.com/morluto/rea/commit/82bbe743336244d398e67512659ea6943d43a4a4)) +* **browser:** preserve payload shapes and WebMCP declarations ([4951a89](https://github.com/morluto/rea/commit/4951a897c53bb6882300c5d7a9660a3f43e374f5)) +* **browser:** release attached viewport overrides without resizing the external page ([f6cfbfc](https://github.com/morluto/rea/commit/f6cfbfcc554ff24173dd7ad5333e8e26ab9c962d)) +* **browser:** retain attached scenario emulation until cleanup ([a0523b3](https://github.com/morluto/rea/commit/a0523b375eb3147f1d2d1e7eb10a2f4546f5d0fc)) +* **browser:** retain malformed redirect diagnostics ([617cd84](https://github.com/morluto/rea/commit/617cd84d27d100e7cc3cd4b5721dea4a996c9775)) +* **browser:** serialize attached scenarios through cleanup settlement ([cfce91d](https://github.com/morluto/rea/commit/cfce91d418fbcde4a9ef283a61549279751854e7)) +* **ci:** scope verification and reuse native runners ([#1344](https://github.com/morluto/rea/issues/1344)) ([d5cb8ae](https://github.com/morluto/rea/commit/d5cb8aee063065a48233458e04771635167825c8)) +* **cli:** avoid duplicate primary cleanup diagnostics ([37fcea7](https://github.com/morluto/rea/commit/37fcea78cecbeeadd869e9a3d77dd133ed264a0a)) +* **cli:** classify JSON input permission denials ([08daf05](https://github.com/morluto/rea/commit/08daf056cc8e4d092f9592574d09d5182457b7bc)) +* **cli:** classify oversized JSON inputs ([f7cf4c8](https://github.com/morluto/rea/commit/f7cf4c890d4b9c70b1f56e6c627b44a59e58fd73)) +* **cli:** stream JSON inputs beyond the whole-document string limit ([#1360](https://github.com/morluto/rea/issues/1360)) ([6ce3288](https://github.com/morluto/rea/commit/6ce3288f3bd65a886e47905455ed5c9b661015e6)), closes [#1331](https://github.com/morluto/rea/issues/1331) +* **cli:** stream JSON results at the shared command boundary ([810107a](https://github.com/morluto/rea/commit/810107a2ad15cc52afd6662aec24d231d8c77225)) +* **contracts:** advertise NUL with a portable hex escape ([3f59a84](https://github.com/morluto/rea/commit/3f59a84bd1039763bb349894542601ed78be2033)), closes [#1329](https://github.com/morluto/rea/issues/1329) +* **contracts:** require observed provider output metadata ([a4ba8ae](https://github.com/morluto/rea/commit/a4ba8aecd507637b6261026afc17f79516840d50)) +* **electron:** preserve unrepresentable numeric option evidence ([41a228c](https://github.com/morluto/rea/commit/41a228c1b01a89127858b1706879ede08a81deaf)) +* **evidence:** order canonical projections independently of locale ([614fb76](https://github.com/morluto/rea/commit/614fb7681ee9e4eba7219c1ee9e90d6a85d78095)) +* **files:** reject nonregular capture and JSON inputs ([5f16124](https://github.com/morluto/rea/commit/5f16124a31fa4a82bd03037506809d6be959d768)) +* **filesystem:** reject unstable artifact targets ([7829b1a](https://github.com/morluto/rea/commit/7829b1aeef8f43f186be2d2adbd6c67541306a7a)) +* **ghidra:** reject a native decompiler built for another host ([#1280](https://github.com/morluto/rea/issues/1280)) ([3728c82](https://github.com/morluto/rea/commit/3728c8267b4fb6da78cbae42a2a6cbddff80ea84)), closes [#1192](https://github.com/morluto/rea/issues/1192) +* **ghidra:** retain process ownership after failed launch rollback ([07675f7](https://github.com/morluto/rea/commit/07675f78c66ce9e8706e808d417265e18ba9f3a5)) +* **ghidra:** verify dense jump tables on an optimized fixture ([#1374](https://github.com/morluto/rea/issues/1374)) ([73a664b](https://github.com/morluto/rea/commit/73a664bc78ee618045a2733b8714821281f77403)) +* **hopper:** allow restart after verified owned-provider shutdown ([1c12349](https://github.com/morluto/rea/commit/1c123493a21cc579ba7532c40e7ef30df45db3e8)) +* **hopper:** probe interior navigation from multi-byte instructions ([#1285](https://github.com/morluto/rea/issues/1285)) ([bf934d5](https://github.com/morluto/rea/commit/bf934d5592e707ba5e7769043de3a430ed8d4923)) +* **ida:** compare admitted document paths consistently ([890bb66](https://github.com/morluto/rea/commit/890bb66b35d5f9f8ee54ff0049bf7dc7b82b2480)) +* **javascript:** avoid positive-zero evidence for signed zero ([9055bd6](https://github.com/morluto/rea/commit/9055bd695b75f72fb1b8a538d1485d30c0b0ee0b)) +* **javascript:** decline source-map UNC references with an unusable host ([#1372](https://github.com/morluto/rea/issues/1372)) ([f504c2a](https://github.com/morluto/rea/commit/f504c2a351027f17ac353fba2d7cfc3505ee17d6)) +* **javascript:** distinguish prefix-only builtins from packages ([2b4abbf](https://github.com/morluto/rea/commit/2b4abbf1ccb6dd6ad1248cf48e381df0842542c1)) +* **javascript:** honor module-sync package exports ([#1361](https://github.com/morluto/rea/issues/1361)) ([d0e6069](https://github.com/morluto/rea/commit/d0e606930acb701790c286340226b1e3e7060b4f)) +* **javascript:** parse declaration artifacts in ambient mode ([4896adc](https://github.com/morluto/rea/commit/4896adcd0f9316034e83129685ed3807ade6f3ea)) +* **javascript:** preserve agreeing module provenance ([db171be](https://github.com/morluto/rea/commit/db171be6e570fd1261a30d711e4da2d17de85a93)) +* **javascript:** preserve capture-time guards and ordering ([001851f](https://github.com/morluto/rea/commit/001851fde6f972e6ebd01fddccdff4c645a85f63)) +* **javascript:** preserve semantic evidence through satisfies ([e995b19](https://github.com/morluto/rea/commit/e995b19f834ba78faa294f5959fd3ad8a97290ca)) +* **javascript:** preserve uncertainty after references escape to calls ([#1292](https://github.com/morluto/rea/issues/1292)) ([355a292](https://github.com/morluto/rea/commit/355a292198bf58245c67ae315fdb4f77e62769cc)) +* **javascript:** reject invalid package exports configurations ([7a4f268](https://github.com/morluto/rea/commit/7a4f2685d41b134507331c322f0f5da8e1f6c3f4)) +* **javascript:** resolve exported callables through lexical bindings ([#1351](https://github.com/morluto/rea/issues/1351)) ([a9f5dad](https://github.com/morluto/rea/commit/a9f5dad5a8f196c88f6305d8d958b355cc0b52c2)) +* **javascript:** resolve query-only HTML references to their document ([55a46f7](https://github.com/morluto/rea/commit/55a46f7c7176075c9edda4fe61ed995f2ceadf6a)) +* **javascript:** retain array identity after length mutations ([4bcea1a](https://github.com/morluto/rea/commit/4bcea1aa76e3e7ca665197181739c5e27a62c40a)) +* **javascript:** retain conditional mutation ordering uncertainty ([b8a8190](https://github.com/morluto/rea/commit/b8a8190b2f30e377eee2d69d1ba31ea454fa70b9)) +* **javascript:** retain distinct module provenance path components ([2bd7de6](https://github.com/morluto/rea/commit/2bd7de6f8ca62fc1d48334cfa7fdced461b7b153)) +* **javascript:** retain unresolved value frontiers in provenance queries ([3e19875](https://github.com/morluto/rea/commit/3e19875c7fa9c61cff655bbe6046ddc4ab558533)) +* **javascript:** store source map URLs once ([ed8fcae](https://github.com/morluto/rea/commit/ed8fcae94b699b62b44162f880faa077a36c455d)) +* **json:** preserve runtime limits across JSON file readers ([#1350](https://github.com/morluto/rea/issues/1350)) ([9c4a68b](https://github.com/morluto/rea/commit/9c4a68bc19a0f7d39557e3cc039f5877f6550f63)) +* **managed:** bind graph facts to their source Evidence ([cc7b5af](https://github.com/morluto/rea/commit/cc7b5af0777fc68ebba10ec061244729ebf2357d)) +* **mcp:** admit composed analysis through result bookkeeping ([e11f4d3](https://github.com/morluto/rea/commit/e11f4d371abaa8cb65ebf7b94fa216329fd78d88)) +* **mcp:** advertise object roots for union input schemas ([#1373](https://github.com/morluto/rea/issues/1373)) ([39dabd0](https://github.com/morluto/rea/commit/39dabd0608ed9617d60f16ece05993089f24ff38)) +* **mcp:** advertise primitive semantic literal seeds ([f62b449](https://github.com/morluto/rea/commit/f62b44971deee0e99df6fcf32758c8e5592400ed)) +* **mcp:** preserve JavaScript workflow identity validation ([#1366](https://github.com/morluto/rea/issues/1366)) ([53ed942](https://github.com/morluto/rea/commit/53ed942a85f51ff9f0e4f01cbb53359df476071d)), closes [#1364](https://github.com/morluto/rea/issues/1364) [#1065](https://github.com/morluto/rea/issues/1065) +* **mcp:** retry failed shutdown resources and retain failure reasons ([e64678e](https://github.com/morluto/rea/commit/e64678e8f9768dd819d8f5f12cc844a6660ff2c5)) +* **native:** distinguish symbol definitions from metadata ([70bad53](https://github.com/morluto/rea/commit/70bad53847b0e14489acee73d204ff645e1adfcd)) +* **native:** preserve unknown Objective-C metadata ([b112d44](https://github.com/morluto/rea/commit/b112d44a3961939881779c81a57e7a3f9d1372f7)) +* **native:** refuse to list architectures of non-Mach-O targets ([#1325](https://github.com/morluto/rea/issues/1325)) ([1b73b5a](https://github.com/morluto/rea/commit/1b73b5ab4bc75bd424e643de8e49f142ffa2b336)) +* **native:** retain LLDB cleanup ownership through client close ([7ad353f](https://github.com/morluto/rea/commit/7ad353fa8b3f07e14face80336678d23cc7c6507)) +* **process:** keep unobserved file contents unknown ([#1358](https://github.com/morluto/rea/issues/1358)) ([f91f279](https://github.com/morluto/rea/commit/f91f2798b4dc6adb61b3ffe28a24a5d55adbd6ff)) +* **process:** retain per-file digest open failures ([415145d](https://github.com/morluto/rea/commit/415145d04f09a15cbfb7dda8ea9dc363a77f9bf0)) +* **reference:** report malformed UTF-8 before import parsing ([f166a2a](https://github.com/morluto/rea/commit/f166a2ae15b072216173a51a8f5cad930a858366)) +* report malformed application evidence as input errors ([218c131](https://github.com/morluto/rea/commit/218c13160ec0ed7116d6633fc76559ec39dae4d7)) +* retain completed observations when later analysis steps fail ([35f121f](https://github.com/morluto/rea/commit/35f121f4acac821e848c485fb82a2c42f51f6ea1)) +* **setup:** install the skill for Claude Code ([b4a1919](https://github.com/morluto/rea/commit/b4a19193fe3baf9075f8ac419517021ea0c71ea3)) +* **setup:** recognize supported Nobara hosts ([f0dc233](https://github.com/morluto/rea/commit/f0dc233d64de4c215c453c346e516b7622713e95)) +* **skill:** pin packaged commands to the shipping package version ([2793672](https://github.com/morluto/rea/commit/2793672ee2a575f97a8011c7fec5288098cdd5d1)) +* **skill:** pin packaged commands to the shipping package version ([#1346](https://github.com/morluto/rea/issues/1346)) ([f39e71c](https://github.com/morluto/rea/commit/f39e71ce1897bb5c704b33a8b0049567f11e3a13)) +* **snapshot:** preserve complete investigation revision histories ([#1354](https://github.com/morluto/rea/issues/1354)) ([1c0cc8a](https://github.com/morluto/rea/commit/1c0cc8a6753b5ac781b28ebb1832f3a6a1771a68)) +* **targets:** cancel resolution before provider admission ([f3c4a33](https://github.com/morluto/rea/commit/f3c4a332f7bd198bd67f0187bc2a85c7b31bb960)) +* **update:** preserve disabled client registrations ([abf5e24](https://github.com/morluto/rea/commit/abf5e243c4d2cae03404b6e1fb1ccc77be917b53)) + + +### Performance Improvements + +* **javascript:** index version relationships once per comparison ([#1347](https://github.com/morluto/rea/issues/1347)) ([b1e85ad](https://github.com/morluto/rea/commit/b1e85ad711743a594c572dbd5b0d5cb664e2a502)) +* **javascript:** validate the version change graph once ([#1370](https://github.com/morluto/rea/issues/1370)) ([037709a](https://github.com/morluto/rea/commit/037709a52c0824f4d2bbee90d8e2642b2d88d364)) +* **json:** encode streamed JSON iteratively ([#1322](https://github.com/morluto/rea/issues/1322)) ([56598be](https://github.com/morluto/rea/commit/56598beb4e82968a313deb9efdf4b98db5bd1f4f)) + + +### Code Refactoring + +* **artifacts:** remove unused root classifier ([5291bca](https://github.com/morluto/rea/commit/5291bca108af781214572fac709f9808bb8aa4db)) +* **artifacts:** test inventory changes at materialization boundary ([750fb65](https://github.com/morluto/rea/commit/750fb6565052e9eaad40b946b6a284d0730d14f8)) +* **browser:** open scenario sessions without a factory wrapper ([d1983a4](https://github.com/morluto/rea/commit/d1983a45767bfcdc020652f48109a78a3f9fa590)) +* **catalog:** import CLI metadata from its owner ([8c96baa](https://github.com/morluto/rea/commit/8c96baab80dc258d31ca1632d761fffb11dbaaae)) +* consolidate boundary semantics and prune redundant tests ([392f1f3](https://github.com/morluto/rea/commit/392f1f310733f2c365da7bc57a1154cf10ec4ba0)) +* **javascript:** normalize erased expression syntax once ([b628bba](https://github.com/morluto/rea/commit/b628bba1fa65fd3b51363bf4b745f0afc57e1dba)) +* **javascript:** parse runtime evidence into one verified owner ([006b295](https://github.com/morluto/rea/commit/006b295f1de19fd5351832cf52d98a202a5cd5cd)) +* **javascript:** remove obsolete scope truncation statistic ([449d570](https://github.com/morluto/rea/commit/449d57075eec71b2f064af8877c50cbbde30a283)) +* **javascript:** share Babel child traversal ([0f10499](https://github.com/morluto/rea/commit/0f10499245ec2fab8823f116caf34450b3a7385b)) +* **javascript:** share semantic evidence at fact construction ([e3bbb9a](https://github.com/morluto/rea/commit/e3bbb9ac453da8d15f3b32511180451613710616)) +* **process:** remove duplicate observation and trace entry points ([070339a](https://github.com/morluto/rea/commit/070339af50a50a0f23e82db859e761c53277ee79)) +* **providers:** use canonical artifact and managed identities ([87f0051](https://github.com/morluto/rea/commit/87f0051496aff1b05ab24d6b63f79884f4ca9b8f)) +* **reference:** simplify malformed UTF-8 handling ([377df71](https://github.com/morluto/rea/commit/377df715ea5b2523cd6c1084fdc286eb8a056182)) +* remove obsolete source exclusions and identity wrapper ([44c92f8](https://github.com/morluto/rea/commit/44c92f88c51841735741811a68cc89fde14efa80)) +* remove single-use forwarding helpers ([4144e45](https://github.com/morluto/rea/commit/4144e454f385c372d29e301e6bb959092c606a6e)) + + +### Documentation + +* add repository-local REA tool design skill ([7738c1f](https://github.com/morluto/rea/commit/7738c1f6a9ccf1ec9868ef832f154abe9ba5eebd)) +* celebrate 40,000 GitHub stars 🎉 ([3edb217](https://github.com/morluto/rea/commit/3edb2172def0e0bd9076f23148f0c41cd2f341a3)) +* celebrate 40,000 GitHub stars 🎉 ([5ecc98a](https://github.com/morluto/rea/commit/5ecc98a5eac4c10d33e9c418b9ffae61c68e3ef2)) +* consolidate agent guidance around ownership and boundaries ([ba44222](https://github.com/morluto/rea/commit/ba4422296dc409d49836f25642555e00463bfe3b)) +* **contracts:** explain canonical URL and skill metadata ownership ([e36afa1](https://github.com/morluto/rea/commit/e36afa112fd7b7ab5a925ca452de93b68f12a6ab)) +* correct MCP error and capture import guidance ([077d6c4](https://github.com/morluto/rea/commit/077d6c407b3ea7443a7277ae0e5531b3927dd742)) +* correct README setup and runtime guidance ([5b3715e](https://github.com/morluto/rea/commit/5b3715ef825a30150b02d3f1bb7d40dd89453018)) +* explain CI scope and native runner reuse ([#1348](https://github.com/morluto/rea/issues/1348)) ([6c9161d](https://github.com/morluto/rea/commit/6c9161d61745e242643f224ce49e7468143a15f3)) +* prune repeated contributor and tool design instructions ([5d79387](https://github.com/morluto/rea/commit/5d79387505ebae1ec8d800ee3ffd901920a9d8be)) +* remove retired architecture and migration artifacts ([7a0c800](https://github.com/morluto/rea/commit/7a0c80085128e6329ca2e4f54f3539f3245c57d1)) + + +### Tests + +* **android:** allow provider readiness under load ([961c3c3](https://github.com/morluto/rea/commit/961c3c3de79ec44d608d011eb3fa3d6bd645cf6a)) +* **artifacts:** verify extraction races with real filesystem changes ([1ac8389](https://github.com/morluto/rea/commit/1ac8389c5c1f75faf8d7f2f3faf2f24febad5fea)) +* **browser:** avoid duplicating source-map listener setup ([9367dc1](https://github.com/morluto/rea/commit/9367dc13bd8d2732d36d5376b5de170c9f4af424)) +* **browser:** report redirect status cases independently ([5a61562](https://github.com/morluto/rea/commit/5a61562dc200120c7b8020854085c17b8203e95d)) +* **cli:** remove duplicate malformed JSON assertion ([5d32e42](https://github.com/morluto/rea/commit/5d32e4252941e93065cadd83b9f02aa6427544d8)) +* exercise source test selection through Git and Vitest ([25711ad](https://github.com/morluto/rea/commit/25711ad2590af136dfb301839dddd6d30971ba76)) +* **filesystem:** bound FIFO regressions at consumers ([0bfb6e0](https://github.com/morluto/rea/commit/0bfb6e00abae1e67a96e548d64954bb21861f621)) +* **ghidra:** allow rollback tests to reach spawned process ([d761d73](https://github.com/morluto/rea/commit/d761d7358b45fe0724b182a206241fd605f338b0)) +* **javascript:** share primitive expansion producer fixtures ([c867bcd](https://github.com/morluto/rea/commit/c867bcd0aadd63473865f9a328459e0db3c89565)) +* **javascript:** share semantic graph test facts ([ac356c4](https://github.com/morluto/rea/commit/ac356c46ad6a17c8864bc5d350984786db62d2f5)) +* **javascript:** verify distinct module origins through reconstruction ([96b2b24](https://github.com/morluto/rea/commit/96b2b245fdefc9c78f5dcf6ce054232b51f7c117)) +* **json:** remove assertions covered by CLI output consumers ([a959a83](https://github.com/morluto/rea/commit/a959a8309db79fbee6477efd7ee541615e625627)) +* **managed:** include shared dossier fixture in artifact inputs ([66a20a2](https://github.com/morluto/rea/commit/66a20a2597b5daebc0a292361aa62a78b7df6e7d)) +* **native:** retain trace diagnostics when observed hits differ ([048b798](https://github.com/morluto/rea/commit/048b79878c70c594789909082499dc675472b63a)) +* **package:** share validated native dossier fixtures ([ca90109](https://github.com/morluto/rea/commit/ca9010936a934a49fbc6cf69eb1d7fc2242b6da9)) +* **process:** publish capture readiness atomically ([74be526](https://github.com/morluto/rea/commit/74be52611e66f680ef1919d521fc3c304bc2326e)) +* **process:** report cleanup details on cancellation failures ([79d5b9a](https://github.com/morluto/rea/commit/79d5b9a826b9204c1ef59b0a5c5ec83e7a2f2bec)) +* **process:** use owned CLI and workspace fixtures ([4940a86](https://github.com/morluto/rea/commit/4940a867e2e56cbb974bfa321008a8f35db47d52)) +* share snapshot replay and managed graph fixtures ([d83cbd2](https://github.com/morluto/rea/commit/d83cbd2abf1bbf15beef990f5353457fdbaaeb8e)) + + +### Continuous Integration + +* enforce architecture guards with portable checkout paths ([ecc67ca](https://github.com/morluto/rea/commit/ecc67cab2d85cacda245890ffe84b80ac395d79e)) + ## [6.2.0](https://github.com/morluto/rea/compare/rea-agents-6.1.0...rea-agents-6.2.0) (2026-10-09) diff --git a/docs/installation.md b/docs/installation.md index c47062a6f..77fc896d5 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -697,7 +697,7 @@ For a client that requires manual configuration, use: "mcpServers": { "rea": { "command": "npx", - "args": ["-y", "rea-agents@6.2.0", "mcp"] + "args": ["-y", "rea-agents@6.3.0", "mcp"] } } } diff --git a/package-lock.json b/package-lock.json index 212d6b8eb..e9bc42c5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "license": "MIT", "dependencies": { "@babel/parser": "8.0.4", diff --git a/package.json b/package.json index 1c41d19bc..69cc9232b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "rea-agents", "mcpName": "io.github.morluto/rea", - "version": "6.2.0", + "version": "6.3.0", "description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.", "license": "MIT", "repository": { diff --git a/server.json b/server.json index 74c21bec1..15253c28c 100644 --- a/server.json +++ b/server.json @@ -8,13 +8,13 @@ "url": "https://github.com/morluto/rea", "source": "github" }, - "version": "6.2.0", + "version": "6.3.0", "packages": [ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", "identifier": "rea-agents", - "version": "6.2.0", + "version": "6.3.0", "runtimeHint": "npx", "transport": { "type": "stdio" diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index 77fc01683..29177bf02 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -1,7 +1,7 @@ /** Generated from package.json and package-lock.json; do not edit. */ export const PACKAGE_METADATA = { name: "rea-agents", - version: "6.2.0", // x-release-please-version + version: "6.3.0", // x-release-please-version serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", From bf58eac4ef0830648db9a67daf6756270fb338e1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:42:17 +0800 Subject: [PATCH 128/189] docs(release): restore complete 6.3 migration and ancestry notes --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ca2fc91d..997d7de24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### ⚠ BREAKING CHANGES +* **captures:** Historical captures without current producer accounting or transaction identity, and web diffs missing accessibility or storage dimensions, are rejected. Preserve original captures and recapture with the current producer; update comparison consumers to include every dimension rather than synthesizing missing observations. See the [process capture guide](docs/process-capture.md) and [browser scenario contract](docs/browser-scenario-contract.md). ([3283a45](https://github.com/morluto/rea/commit/3283a45d09457c79e3adadb50a48620926d4bc5b)) * **browser:** JSON shape paths now contain typed property and array-element segments. WebMCP input_schema_shape is replaced by input_schema and input_schema_sha256, retaining declared examples and defaults. * **process:** Filesystem digest omission entries now require system_code; budget and changed-file omissions use null, and unavailable-file omissions preserve the operating-system error code. * **contracts:** Provider analysis outputs must explicitly supply metadata previously repaired with defaults; unsupported nullable facets must be reported as null. @@ -15,11 +16,13 @@ ### Features +* **setup:** register OMP during setup ([#1301](https://github.com/morluto/rea/pull/1301)) ([8b4c359](https://github.com/morluto/rea/commit/8b4c3591358ee59297d8298ede1b63d08459d817)) * **javascript:** record Electron integrity mismatches ([7915ee5](https://github.com/morluto/rea/commit/7915ee51781878ed67e094259924b6e6f3093b3f)) ### Bug Fixes +* **inspector:** retain observations after capture failures ([dea3498](https://github.com/morluto/rea/commit/dea3498b2b8d919606eefc4fd62f6ebcbbe5ed30)) * **artifacts:** bind ASAR interpretation to owned snapshots ([d79317c](https://github.com/morluto/rea/commit/d79317cda0bbe8240eb7e25b0a5de90dcffca5fa)) * **artifacts:** infer legacy Mach-O simulator platforms ([5aa2002](https://github.com/morluto/rea/commit/5aa200285ab066e48b37b716495936e6e2a963fd)) * **artifacts:** preserve archive facts and Unicode path identity ([5751f5c](https://github.com/morluto/rea/commit/5751f5caac86c770123ae739a4e4101a72b0989c)) @@ -101,6 +104,7 @@ ### Code Refactoring +* use canonical implementations and types directly ([765e809](https://github.com/morluto/rea/commit/765e809e366eff21b4b9c224f1a813ad64245ea3)) * **artifacts:** remove unused root classifier ([5291bca](https://github.com/morluto/rea/commit/5291bca108af781214572fac709f9808bb8aa4db)) * **artifacts:** test inventory changes at materialization boundary ([750fb65](https://github.com/morluto/rea/commit/750fb6565052e9eaad40b946b6a284d0730d14f8)) * **browser:** open scenario sessions without a factory wrapper ([d1983a4](https://github.com/morluto/rea/commit/d1983a45767bfcdc020652f48109a78a3f9fa590)) @@ -120,6 +124,9 @@ ### Documentation +* keep license sections text-only ([e10f1f0](https://github.com/morluto/rea/commit/e10f1f0901fa56fb4443837cf9528b31a12e140e)) +* align translated README artwork and layout ([ccfbe87](https://github.com/morluto/rea/commit/ccfbe87e984e456e12c66d0d2fe6d5a559d09518)) +* add README artwork and refine closing sections ([4b8e744](https://github.com/morluto/rea/commit/4b8e744d90579e353371649047215c4e4be7a5f6)) * add repository-local REA tool design skill ([7738c1f](https://github.com/morluto/rea/commit/7738c1f6a9ccf1ec9868ef832f154abe9ba5eebd)) * celebrate 40,000 GitHub stars 🎉 ([3edb217](https://github.com/morluto/rea/commit/3edb2172def0e0bd9076f23148f0c41cd2f341a3)) * celebrate 40,000 GitHub stars 🎉 ([5ecc98a](https://github.com/morluto/rea/commit/5ecc98a5eac4c10d33e9c418b9ffae61c68e3ef2)) @@ -134,6 +141,8 @@ ### Tests +* share the client registration command to restore the jscpd gate ([#1317](https://github.com/morluto/rea/pull/1317)) ([5d16be2](https://github.com/morluto/rea/commit/5d16be2a7185db8b70a5fcbc5f5e1be63297f2c8)) +* **mcp:** remove arbitrary schema inventory thresholds ([24673aa](https://github.com/morluto/rea/commit/24673aaae497ca4ef0902544c0cd69817f5424ed)) * **android:** allow provider readiness under load ([961c3c3](https://github.com/morluto/rea/commit/961c3c3de79ec44d608d011eb3fa3d6bd645cf6a)) * **artifacts:** verify extraction races with real filesystem changes ([1ac8389](https://github.com/morluto/rea/commit/1ac8389c5c1f75faf8d7f2f3faf2f24febad5fea)) * **browser:** avoid duplicating source-map listener setup ([9367dc1](https://github.com/morluto/rea/commit/9367dc13bd8d2732d36d5376b5de170c9f4af424)) From 40f632a155bff2defdea09e467229c703bc0b0e9 Mon Sep 17 00:00:00 2001 From: GRAB Racem Date: Sat, 10 Oct 2026 02:06:15 +0200 Subject: [PATCH 129/189] ci: re-run the suite after the main-branch shard flake The failed shard is the JavaScriptSemanticGraphBuilder short-circuit mutation test, which also failed on main run 38003459598 at the same base commit (08ec2bf8) before this branch started CI, and passed on main run 38003459600 minutes later at the same commit. From e17290cd2a17931d7a2af70f74b76b94276bd788 Mon Sep 17 00:00:00 2001 From: GRAB Racem Date: Sat, 10 Oct 2026 02:34:52 +0200 Subject: [PATCH 130/189] ci: re-run the suite on the corrected main checkpoint b8a8190b restored the guarded-mutation uncertainty the failing test encodes, so the shard should pass against the new merge base. From e4a8e0b728154fe0bf181684ccd0d73df45cf4bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 00:44:32 +0000 Subject: [PATCH 131/189] fix(javascript): recognize Electron APIs through renamed bindings Electron recognition matched callee spellings, so a bundler rename such as esbuild's `import { ipcMain as ipcMain2 } from "electron"`, or a destructured `const { contextBridge: bridge } = require("electron")`, hid every IPC handler, BrowserWindow, contextBridge and utility process behind it. Resolve each call and construction root lexically to its Electron import or require origin, and classify the callee under that export's name. Shadowed locals keep their own meaning. On Hermes Desktop v0.21.6, whose main process is one esbuild ESM bundle, recognized main IPC handlers rise from 1 to 204, BrowserWindow constructions from 0 to 11, and paired renderer transmissions from 1 to 201. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01XPY2GmufMNGQKoEgRUx1pd --- .../electronStaticAnalysisBrowser.ts | 8 +- .../javascript/electronStaticAnalysisIpc.ts | 3 +- .../electronStaticAnalysisValues.ts | 21 ++++- .../javascript/javascriptSemanticAnalysis.ts | 79 +++++++++++++++++++ .../javascript/javascriptStaticAnalysis.ts | 27 +++---- .../javascriptStaticAnalysisState.ts | 2 + .../electronApplicationAnalysis.test.ts | 66 ++++++++++++++++ 7 files changed, 186 insertions(+), 20 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisBrowser.ts b/src/domain/javascript/electronStaticAnalysisBrowser.ts index f29e7cf8f..a44baf89a 100644 --- a/src/domain/javascript/electronStaticAnalysisBrowser.ts +++ b/src/domain/javascript/electronStaticAnalysisBrowser.ts @@ -12,6 +12,7 @@ import type { import { boundedExpression, collectContextBridgeMembers, + electronCalleeName, electronStaticValue, objectProperty, } from "./electronStaticAnalysisValues.js"; @@ -19,7 +20,6 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js"; import { argumentNode, - calleeName, range, staticPath, staticPathResolutionContext, @@ -42,7 +42,7 @@ const inspectBrowserWindow = ( node: t.NewExpression, context: JavaScriptFindingContext, ): void => { - const name = calleeName(node.callee); + const name = electronCalleeName(node.callee, context); if (name !== "BrowserWindow" && !name.endsWith(".BrowserWindow")) return; const options = argumentNode(node.arguments[0]); const collected = collectWindowOptions(context.source, options); @@ -165,7 +165,7 @@ const inspectContextBridge = ( node: t.CallExpression, context: JavaScriptFindingContext, ): void => { - const name = calleeName(node.callee); + const name = electronCalleeName(node.callee, context); const main = name === "contextBridge.exposeInMainWorld" || name.endsWith(".contextBridge.exposeInMainWorld"); @@ -213,7 +213,7 @@ const inspectUtilityProcess = ( node: t.CallExpression, context: JavaScriptFindingContext, ): void => { - const name = calleeName(node.callee); + const name = electronCalleeName(node.callee, context); if (name !== "utilityProcess.fork" && !name.endsWith(".utilityProcess.fork")) return; const moduleNode = argumentNode(node.arguments[0]); diff --git a/src/domain/javascript/electronStaticAnalysisIpc.ts b/src/domain/javascript/electronStaticAnalysisIpc.ts index 9efc2670b..a560ea184 100644 --- a/src/domain/javascript/electronStaticAnalysisIpc.ts +++ b/src/domain/javascript/electronStaticAnalysisIpc.ts @@ -7,6 +7,7 @@ import type { } from "./electronStaticAnalysisTypes.js"; import { boundedExpression, + electronCalleeName, electronStaticValue, handlerKind, } from "./electronStaticAnalysisValues.js"; @@ -36,7 +37,7 @@ const inspectIpcCall = ( node: t.CallExpression, context: JavaScriptFindingContext, ): void => { - const name = calleeName(node.callee); + const name = electronCalleeName(node.callee, context); const descriptor = ipcDescriptor(name); if (descriptor === undefined) return; const channelNode = argumentNode(node.arguments[0]); diff --git a/src/domain/javascript/electronStaticAnalysisValues.ts b/src/domain/javascript/electronStaticAnalysisValues.ts index 2a800e6bb..c2bb6e76a 100644 --- a/src/domain/javascript/electronStaticAnalysisValues.ts +++ b/src/domain/javascript/electronStaticAnalysisValues.ts @@ -6,7 +6,26 @@ import { readExactJavaScriptLiteral, semanticStaticPropertyName, } from "./javascriptAstValues.js"; -import { sourceSlice } from "./javascriptStaticAnalysisHelpers.js"; +import { calleeName, sourceSlice } from "./javascriptStaticAnalysisHelpers.js"; +import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js"; + +/** Name a callee, spelling a root renamed from Electron as its export. */ +export const electronCalleeName = ( + callee: t.Node, + context: JavaScriptFindingContext, +): string => { + const name = calleeName(callee); + let root = callee; + while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) { + if (!t.isNode(root.object)) return name; + root = root.object; + } + if (!t.isIdentifier(root)) return name; + const exported = context.electronBindings?.get(root.start ?? -1); + return exported === undefined + ? name + : `${exported}${name.slice(root.name.length)}`; +}; /** Preserve one literal value or the exact inert expression. */ export const electronStaticValue = ( diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 5a873429e..b5c1c7f5d 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -29,6 +29,7 @@ import { semanticVariableScope, } from "./javascriptSemanticState.js"; import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; +import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js"; import { collectSemanticMemberMutations } from "./javascriptSemanticMemberMutations.js"; import { collectSemanticReturns, @@ -282,6 +283,84 @@ const resolveGlobalAliasFact = ( return openGlobalFact(name); }; +const ELECTRON_MODULE = /^electron(?:\/(?:common|main|renderer|utility))?$/u; + +/** + * Electron export paths for call and construction roots bound to Electron + * under another name, such as esbuild's `import { ipcMain as ipcMain2 }`. + * Keys are root identifier offsets; roots spelled as their export are omitted. + */ +export const classifyParsedJavaScriptElectronBindings = ( + file: ParsedJavaScriptSource, +): ReadonlyMap => { + const facts = new Map(); + const state = createState(file.program); + collectDefinitions(file.program, state); + const exportsByBinding = new Map(); + traverseJavaScriptAst(file.program, { + enter: (node) => { + if ( + !t.isCallExpression(node) && + !t.isOptionalCallExpression(node) && + !t.isNewExpression(node) + ) + return; + const root = calleeRoot(node.callee); + if (root === undefined) return; + const binding = resolveSemanticBindingState(state, root, root.name); + if (binding === undefined) return; + let exported = exportsByBinding.get(binding.bindingId); + if (exported === undefined) { + exported = electronExport(binding, state); + exportsByBinding.set(binding.bindingId, exported); + } + if (exported !== null && exported !== root.name) + facts.set(root.start ?? -1, exported); + }, + }); + return facts; +}; + +const calleeRoot = (node: t.Node): t.Identifier | undefined => { + while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) { + if (!t.isNode(node.object)) return undefined; + node = node.object; + } + return t.isIdentifier(node) ? node : undefined; +}; + +// Read import and require origins directly; general value evaluation is +// unnecessary here and costly across large vendor bundles. +const electronExport = ( + binding: JavaScriptSemanticBindingState, + state: JavaScriptSemanticAnalysisState, +): string | null => { + const origin = bindingOrigin(binding, state); + return origin !== undefined && + ELECTRON_MODULE.test(origin.specifier) && + origin.importedPath.length > 0 + ? origin.importedPath.join(".") + : null; +}; + +const bindingOrigin = ( + binding: JavaScriptSemanticBindingState, + state: JavaScriptSemanticAnalysisState, +): JavaScriptModuleOrigin | undefined => { + if (binding.directOrigins.length > 0) + return binding.directOrigins.length === 1 + ? binding.directOrigins[0] + : undefined; + const [initializer] = binding.initializers; + if (binding.mutable || binding.initializers.length !== 1) return undefined; + const origin = semanticRequireOrigin(initializer?.node, state); + const projection = initializer?.projection ?? []; + return origin === undefined || + !projection.every((key): key is string => typeof key === "string") + ? undefined + : { ...origin, importedPath: [...origin.importedPath, ...projection] }; +}; + const createState = (program: t.Program): JavaScriptSemanticAnalysisState => { const root: JavaScriptSemanticScopeState = { scopeId: semanticScopeId("program", program), diff --git a/src/domain/javascript/javascriptStaticAnalysis.ts b/src/domain/javascript/javascriptStaticAnalysis.ts index af20eaa92..524af811e 100644 --- a/src/domain/javascript/javascriptStaticAnalysis.ts +++ b/src/domain/javascript/javascriptStaticAnalysis.ts @@ -25,9 +25,11 @@ import { finalizeLocatedFindings } from "./javascriptStaticAnalysisFindings.js"; import { createJavaScriptAnalysisAccumulator, type JavaScriptAnalysisAccumulator as AnalysisAccumulator, + type JavaScriptFindingContext, } from "./javascriptStaticAnalysisState.js"; import type { JavaScriptStaticAnalysis } from "./javascriptStaticAnalysisTypes.js"; import { + classifyParsedJavaScriptElectronBindings, classifyParsedJavaScriptOpenReceivers, type JavaScriptOpenReceiverFact, } from "./javascriptSemanticAnalysis.js"; @@ -57,21 +59,24 @@ export const analyzeParsedJavaScriptStaticSource = ( openReceiverFacts?: ReadonlyMap, ): JavaScriptStaticAnalysis => { const accumulator = createJavaScriptAnalysisAccumulator(source.length); - traverseStaticSource(source, file, accumulator, openReceiverFacts); + traverseStaticSource(file, { + source, + accumulator, + ...(openReceiverFacts === undefined ? {} : { openReceiverFacts }), + electronBindings: classifyParsedJavaScriptElectronBindings(file), + }); addSourceMapDirectives(source, file.comments ?? [], accumulator); return finalizeStaticAnalysis(source, file, accumulator); }; const traverseStaticSource = ( - source: string, file: ParsedJavaScriptSource, - accumulator: AnalysisAccumulator, - openReceiverFacts?: ReadonlyMap, + findings: JavaScriptFindingContext, ): void => { traverseJavaScriptAst(file, { enter: (node) => { - accumulator.visitedNodes += 1; - inspectNode(source, node, accumulator, openReceiverFacts); + findings.accumulator.visitedNodes += 1; + inspectNode(node, findings); return undefined; }, }); @@ -156,16 +161,10 @@ const finalizeStaticAnalysis = ( }; const inspectNode = ( - source: string, node: t.Node, - accumulator: AnalysisAccumulator, - openReceiverFacts?: ReadonlyMap, + findings: JavaScriptFindingContext, ): void => { - const findings = { - source, - accumulator, - ...(openReceiverFacts === undefined ? {} : { openReceiverFacts }), - }; + const { source, accumulator } = findings; inspectElectronStaticNode(node, findings); if (t.isCallExpression(node)) { inspectBundlerRegistration(source, node, accumulator); diff --git a/src/domain/javascript/javascriptStaticAnalysisState.ts b/src/domain/javascript/javascriptStaticAnalysisState.ts index 23de6952b..47e25bccd 100644 --- a/src/domain/javascript/javascriptStaticAnalysisState.ts +++ b/src/domain/javascript/javascriptStaticAnalysisState.ts @@ -65,6 +65,8 @@ export interface JavaScriptFindingContext { | "local-indexed-db" | "local-cache-storage" >; + /** Electron export paths for renamed call roots, by identifier offset. */ + readonly electronBindings?: ReadonlyMap; } /** Candidate import, require, worker, or service-worker reference. */ diff --git a/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts b/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts index 3484f98a2..4180e1818 100644 --- a/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts +++ b/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts @@ -89,6 +89,33 @@ describe("static Electron application analysis", () => { expect(requestedMembers).toEqual(["*"]); }); + it("maps Electron boundaries through bundler-renamed bindings", async () => { + const root = await renamedBindingFixtureDirectory(); + + const result = await reconstructJavaScriptArtifact({ input_path: root }); + const graph = parseJavaScriptApplicationGraph(result.graph); + const handledChannels = graph.nodes.flatMap(({ kind, observations }) => + kind === "ipc-handler" + ? observations.flatMap(({ properties }) => + properties.side === "main" ? [properties.channel] : [], + ) + : [], + ); + + expect(result.electron_summary).toMatchObject({ + browser_windows: 1, + context_bridge_apis: 1, + exposed_api_members: 2, + ipc: { + main_handlers: 2, + paired_renderer_transmissions: 2, + unpaired_literal_renderer_transmissions: 0, + }, + utility_processes: 1, + }); + expect(handledChannels.sort()).toEqual(["rea:read", "rea:write"]); + }); + it("returns a tagged cancellation without executing application code", async () => { const root = await fixtureDirectory(); const controller = new AbortController(); @@ -299,6 +326,45 @@ const fixtureDirectory = async (): Promise => { return root; }; +const renamedBindingFixtureDirectory = async (): Promise => { + const root = await createTestTempDirectory("rea-electron-renamed-"); + await Promise.all([ + writeFile( + join(root, "package.json"), + JSON.stringify({ name: "rea-electron-renamed", main: "main.mjs" }), + ), + // Bundlers rename colliding imports, e.g. esbuild's ipcMain2. + writeFile( + join(root, "main.mjs"), + String.raw` +import { BrowserWindow as BrowserWindow2, ipcMain as ipcMain2 } from "electron"; +import { ipcMain as ipcMain3, utilityProcess as utility } from "electron/main"; + +new BrowserWindow2({ webPreferences: { preload: "./preload.cjs" } }); +ipcMain2.handle("rea:read", async () => "value"); +ipcMain3.on("rea:write", () => undefined); +utility.fork("./worker.js"); +function register(ipcMain2) { + ipcMain2.handle("rea:shadowed", async () => "local"); +} +export { register }; +`, + ), + writeFile( + join(root, "preload.cjs"), + String.raw` +const { contextBridge: bridge, ipcRenderer: ipc } = require("electron"); +bridge.exposeInMainWorld("reaApi", { + read: () => ipc.invoke("rea:read"), + write: (value) => ipc.send("rea:write", value), +}); +`, + ), + writeFile(join(root, "worker.js"), "module.exports = {};"), + ]); + return root; +}; + const computedMemberFixtureDirectory = async (): Promise => { const root = await createTestTempDirectory("rea-electron-computed-members-"); await mkdir(join(root, "native")); From 5fc4d792caeb3cd81c2021e45a158c5127906c56 Mon Sep 17 00:00:00 2001 From: Minghang Chamling <133689405+cold-atom@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:24:38 +0800 Subject: [PATCH 132/189] fix(javascript): handle oversized inline source maps (#1386) * fix(javascript): handle oversized inline source maps * fix(javascript): avoid source map directive regex overflow --- .../javascriptStaticAnalysisCalls.ts | 33 +++++++++--- ...javascriptStaticAnalysisSourceMaps.test.ts | 54 +++++++++++++++++++ 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/domain/javascript/javascriptStaticAnalysisCalls.ts b/src/domain/javascript/javascriptStaticAnalysisCalls.ts index e7c8ee182..5137e1ebd 100644 --- a/src/domain/javascript/javascriptStaticAnalysisCalls.ts +++ b/src/domain/javascript/javascriptStaticAnalysisCalls.ts @@ -306,13 +306,32 @@ export const addSourceMapDirectives = ( end === null ) continue; - const match = /^(?:\/\/|\/\*)[#@]\s*sourceMappingURL\s*=\s*([^\s*]+)/u.exec( - source.slice(start, end), - ); - if (match === null) continue; - const declared = match[1]; - if (declared === undefined || declared.length === 0) continue; - const location = rangeForOffsets(source, start, start + match[0].length); + const commentSource = source.slice(start, end); + if ( + !(commentSource.startsWith("//") || commentSource.startsWith("/*")) || + !(commentSource[2] === "#" || commentSource[2] === "@") + ) + continue; + // Single-class searches avoid regex backtracking over unbounded whitespace + // or inline URLs, which can exhaust the engine stack on two-byte strings. + const nameOffset = commentSource.slice(3).search(/\S/u); + if (nameOffset === -1) continue; + const nameStart = 3 + nameOffset; + if (!commentSource.startsWith("sourceMappingURL", nameStart)) continue; + const nameEnd = nameStart + "sourceMappingURL".length; + const equalsOffset = commentSource.slice(nameEnd).search(/\S/u); + if (equalsOffset === -1) continue; + const equalsStart = nameEnd + equalsOffset; + if (!commentSource.startsWith("=", equalsStart)) continue; + const urlOffset = commentSource.slice(equalsStart + 1).search(/\S/u); + if (urlOffset === -1) continue; + const declaredStart = equalsStart + 1 + urlOffset; + const terminator = commentSource.slice(declaredStart).search(/[\s*]/u); + const declaredEnd = + terminator === -1 ? commentSource.length : declaredStart + terminator; + if (declaredEnd === declaredStart) continue; + const declared = commentSource.slice(declaredStart, declaredEnd); + const location = rangeForOffsets(source, start, start + declaredEnd); addFindingOnce(accumulator, `source-map\0${declared}`, () => accumulator.sourceMaps.push({ declared_url: declared, location }), ); diff --git a/src/domain/javascript/javascriptStaticAnalysisSourceMaps.test.ts b/src/domain/javascript/javascriptStaticAnalysisSourceMaps.test.ts index 93a9ddec9..f5664f73c 100644 --- a/src/domain/javascript/javascriptStaticAnalysisSourceMaps.test.ts +++ b/src/domain/javascript/javascriptStaticAnalysisSourceMaps.test.ts @@ -30,6 +30,60 @@ describe("source map directives", () => { ).toEqual(["first.map", "second.map"]); }); + it("reads a large inline map from a two-byte source without overflowing", () => { + const declared = + "data:application/json;charset=utf-8;base64," + "A".repeat(9_000_000); + const source = `const label = "ğ";\n//# sourceMappingURL=${declared}`; + + expect(sourceMapUrls(source)).toEqual([declared]); + }); + + it.each([ + ["after the marker", "//#", "sourceMappingURL=x"], + ["before the equals sign", "//# sourceMappingURL", "=x"], + ["before the URL", "//# sourceMappingURL=", "x"], + ])("reads 9.5M spaces %s without overflowing", (_label, prefix, suffix) => { + const source = `ğ${prefix}${" ".repeat(9_500_000)}${suffix}`; + expect(analyzeJavaScriptStaticSource(source).source_map_urls).toEqual([ + { + declared_url: "x", + location: { + start: { line: 1, column: 1 }, + end: { line: 1, column: source.length }, + }, + }, + ]); + }); + + it.each([ + "//#", + "//# \t", + "//# sourceMappingURL", + "//# sourceMappingURL \t", + "//# sourceMappingURL=", + "//# sourceMappingURL= \t", + "/*# sourceMappingURL= */", + "//# sourceMappingURLx=app.js.map", + "//# sourceMappingURL app.js.map", + ])("ignores an incomplete or malformed directive: %s", (source) => { + expect(sourceMapUrls(source)).toEqual([]); + }); + + it("preserves Unicode whitespace and URL terminator boundaries", () => { + const source = + "ğ/*@\u00a0sourceMappingURL\u2003=\ufeffapp.js.map* ignored */"; + const declaredEnd = source.indexOf("* ignored"); + expect(analyzeJavaScriptStaticSource(source).source_map_urls).toEqual([ + { + declared_url: "app.js.map", + location: { + start: { line: 1, column: 1 }, + end: { line: 1, column: declaredEnd }, + }, + }, + ]); + }); + it("reports nothing when no directive is present", () => { expect(sourceMapUrls("const value = 1;")).toEqual([]); }); From 498cec042a5f05557ae9c2ef9663d41dd03901c3 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:29:20 -0700 Subject: [PATCH 133/189] fix(cli): stop advertising multi-letter single-dash option aliases (#1395) Incur's `alias` map registers one-letter short flags and already accepts kebab-case spellings of camelCase options. Twenty options registered their kebab-case long name as an "alias", so help and completions advertised flags such as `-case-sensitive` and `-relative-path` that the parser reads as stacked short flags and rejects with "Unknown flag: -c". Co-authored-by: Claude Opus 5.5 --- src/cli/artifactCommands.ts | 9 --- src/cli/coreBinaryCommands.ts | 5 -- src/cli/coreNativeCommands.ts | 13 ---- src/cli/electronCommands.ts | 1 - src/cli/setupCommands.ts | 1 - src/cli/utilityCommands.ts | 5 -- tests/boundary/cli/cliOptionAliases.test.ts | 71 +++++++++++++++++++++ 7 files changed, 71 insertions(+), 34 deletions(-) create mode 100644 tests/boundary/cli/cliOptionAliases.test.ts diff --git a/src/cli/artifactCommands.ts b/src/cli/artifactCommands.ts index 55e465711..5f6957930 100644 --- a/src/cli/artifactCommands.ts +++ b/src/cli/artifactCommands.ts @@ -123,7 +123,6 @@ const registerAssetCatalogCommand = ( .default(1_000) .describe("Maximum records to return"), }), - alias: {}, run: ({ args, options }) => logCliCommand(logger, CLI_COMMANDS.inspectAssetCatalog, () => runProviderAnalysis( @@ -170,11 +169,6 @@ const registerInterfaceBuilderCommand = ( .default(40_000) .describe("Maximum decoded connections"), }), - alias: { - maxDocuments: "max-documents", - maxObjects: "max-objects", - maxConnections: "max-connections", - }, run: ({ args, options }) => logCliCommand(logger, "decode-interface-builder", () => runProviderAnalysis( @@ -233,9 +227,6 @@ const registerInspectionCommand = ( .default("fail") .describe("Behavior when declared artifact integrity does not match"), }), - alias: { - integrityPolicy: "integrity-policy", - }, run: ({ args, options }) => logCliCommand(logger, "inspect-artifact", () => runProviderAnalysis( diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index a916a2c5a..cf4a08236 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -54,7 +54,6 @@ const registerOverviewCommands = ( options: overviewOptions.extend({ integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy, }), - alias: { integrityPolicy: "integrity-policy" }, run: async ({ args, options }) => { // Route JavaScript targets exactly like analyze-javascript-application, // including typed cancellation; cancellation wraps logging so its exit @@ -274,9 +273,6 @@ const registerTraceCommand = ( "target-format": formatSelectionOption, provider: providerSelectionOption, }), - alias: { - caseSensitive: "case-sensitive", - }, run: ({ args, options }) => logCliCommand(logger, "trace", () => runDirectAnalysis( @@ -455,7 +451,6 @@ const registerSearchCommand = ( "target-format": formatSelectionOption, provider: providerSelectionOption, }), - alias: { caseSensitive: "case-sensitive" }, run: ({ args, options }) => logCliCommand(logger, "search", () => runDirectAnalysis( diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts index 51849bcf6..a00f41cdf 100644 --- a/src/cli/coreNativeCommands.ts +++ b/src/cli/coreNativeCommands.ts @@ -157,13 +157,6 @@ export const registerCoreNativeCommands = ( "target-format": formatSelectionOption, provider: providerSelectionOption, }), - alias: { - maxDepth: "max-depth", - maxFunctions: "max-functions", - maxCallSites: "max-call-sites", - maxNodes: "max-nodes", - maxEdges: "max-edges", - }, run: ({ args, options }) => logCliCommand(logger, CLI_COMMANDS.traceNativeValues, () => runDirectAnalysis( @@ -283,7 +276,6 @@ const registerNativeDispatchMetadataCommand = ( "target-format": formatSelectionOption, provider: providerSelectionOption, }), - alias: { maxRecords: "max-records" }, run: async ({ args, options }) => logCliCommand(logger, "inspect-native-dispatch-metadata", () => runDirectAnalysis( @@ -343,11 +335,6 @@ const registerNativeUiActionCommand = ( "target-format": formatSelectionOption, provider: providerSelectionOption, }), - alias: { - maxDepth: "max-depth", - maxNodes: "max-nodes", - maxEdges: "max-edges", - }, run: async ({ args, options }) => logCliCommand(logger, "trace-native-ui-action", () => runDirectAnalysis( diff --git a/src/cli/electronCommands.ts b/src/cli/electronCommands.ts index 73e59fec5..93f99163a 100644 --- a/src/cli/electronCommands.ts +++ b/src/cli/electronCommands.ts @@ -190,7 +190,6 @@ const registerJavaScriptApplicationCommand = ( path: z.string().describe("ASAR or extracted application path"), }), options: javascriptApplicationOptions, - alias: { integrityPolicy: "integrity-policy" }, run: ({ args, options }) => withCommandCancellation((signal) => logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () => diff --git a/src/cli/setupCommands.ts b/src/cli/setupCommands.ts index d4e520970..7be736898 100644 --- a/src/cli/setupCommands.ts +++ b/src/cli/setupCommands.ts @@ -148,7 +148,6 @@ const registerMaintenanceCommands = ( .default(false) .describe("Also remove REA caches and state"), }), - alias: { purgeData: "purge-data" }, run: ({ options }) => logCliCommand( logger, diff --git a/src/cli/utilityCommands.ts b/src/cli/utilityCommands.ts index 9b8696bcd..0c4f79c5a 100644 --- a/src/cli/utilityCommands.ts +++ b/src/cli/utilityCommands.ts @@ -65,10 +65,6 @@ export const registerUtilityCommands = ( .default(500) .describe("Maximum accessibility nodes per capture"), }), - alias: { - windowId: "window-id", - maxNodes: "max-nodes", - }, run: ({ args, options }) => logCliCommand(logger, command, async () => { const parameters = { @@ -172,7 +168,6 @@ const registerNativeCommands = ( "Plist path relative to the app root (default: Contents/Info.plist)", ), }), - alias: { relativePath: "relative-path" }, run: ({ args, options }) => logCliCommand(logger, "inspect-plist", () => runProviderAnalysis( diff --git a/tests/boundary/cli/cliOptionAliases.test.ts b/tests/boundary/cli/cliOptionAliases.test.ts new file mode 100644 index 000000000..4bdedf2da --- /dev/null +++ b/tests/boundary/cli/cliOptionAliases.test.ts @@ -0,0 +1,71 @@ +import { Cli } from "incur"; +import { describe, expect, it } from "vitest"; + +import { createCli } from "../../../src/cli.js"; +import { createCliInventory } from "../../../scripts/lib/catalog-cli.mjs"; + +type CliInstance = ReturnType; +type CommandMap = NonNullable>; + +const registeredCommands: WeakMap = Cli.toCommands; + +const serve = async ( + cli: CliInstance, + argv: readonly string[], +): Promise<{ readonly stdout: string; readonly exitCode: number }> => { + let stdout = ""; + let exitCode = 0; + await cli.serve([...argv], { + env: {}, + exit: (code) => { + exitCode = code; + }, + stdout: (text) => { + stdout += text; + }, + }); + return { stdout, exitCode }; +}; + +const registeredAliases = ( + cli: CliInstance, + command: string, +): Record => { + const entry = registeredCommands.get(cli)?.get(command); + const alias: unknown = + entry === undefined ? undefined : Reflect.get(entry, "alias"); + return typeof alias === "object" && alias !== null ? { ...alias } : {}; +}; + +describe("CLI option aliases", () => { + it("register only single-character short flags", async () => { + const cli = createCli({}); + const invalid: string[] = []; + for (const command of createCliInventory(cli).primary) { + for (const [option, short] of Object.entries( + registeredAliases(cli, command), + )) + if (typeof short !== "string" || short.length !== 1) + invalid.push(`${command} ${option}: ${String(short)}`); + // Incur parses `-abc` as stacked one-letter flags, so help must never + // advertise a multi-letter single-dash spelling. + const help = await serve(cli, [command, "--help"]); + for (const match of help.stdout.matchAll(/(?:^|[\s,])-([a-z][\w-]+)/gmu)) + invalid.push(`${command} help: -${match[1] ?? ""}`); + } + expect(invalid).toEqual([]); + }); + + it("accepts kebab-case long options without registered aliases", async () => { + const cli = createCli({}); + const result = await serve(cli, [ + "inspect-plist", + "/nonexistent/REA.app", + "--relative-path", + "Contents/Info.plist", + "--json", + ]); + expect(result.stdout).not.toContain("Unknown flag"); + expect(result.stdout).toContain("/nonexistent/REA.app"); + }); +}); From 2b6e9ec03f88abb0799a4d154e48544ff4685a41 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:29:31 -0700 Subject: [PATCH 134/189] fix(browser): classify selected web trace file failures by cause (#1396) trace_web_module_imports and trace_web_source_location reported a missing or non-file manifest, source map or import map as artifact_operation_failed ("Artifact could not be read or written" / "unsafe or conflicting internal path"). These are caller selections: report ENOENT/ENOTDIR and non-regular files as invalid input on the selected field, and EACCES/EPERM as a host access denial. A missing manifest-derived source file stays an artifact fault. Co-authored-by: Claude Opus 5.5 --- src/browser/assets/LocalWebScriptArtifacts.ts | 4 +- src/browser/assets/WebArtifactReads.ts | 37 ++++++++ .../assets/WebSourceLocationArtifacts.ts | 1 + src/browser/modules/WebModuleArtifacts.ts | 1 + .../filesystem/webModuleArtifacts.test.ts | 92 +++++++++++++++++-- .../webSourceLocationArtifacts.test.ts | 21 +++-- 6 files changed, 138 insertions(+), 18 deletions(-) diff --git a/src/browser/assets/LocalWebScriptArtifacts.ts b/src/browser/assets/LocalWebScriptArtifacts.ts index 985756a73..c5d6ea8ed 100644 --- a/src/browser/assets/LocalWebScriptArtifacts.ts +++ b/src/browser/assets/LocalWebScriptArtifacts.ts @@ -25,6 +25,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort { async load(input: SelectedWebScriptInput, options?: ExecutionOptions) { let field: readonly (string | number)[] = ["manifest_path"]; let targetPath = input.manifest_path; + let callerSelected = true; try { const manifestBytes = await readWebArtifactJson( input.manifest_path, @@ -58,6 +59,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort { const root = resolve(dirname(input.manifest_path)); const sourcePath = join(root, "files", portable); targetPath = sourcePath; + callerSelected = false; await assertContained(root, sourcePath); const sourceBytes = await readStableArtifact( sourcePath, @@ -99,7 +101,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort { return err( webArtifactReadError( cause, - { operation: this.operation, field, targetPath }, + { operation: this.operation, field, targetPath, callerSelected }, options?.signal, ), ); diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index ee38a9016..cd142f62f 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -3,6 +3,7 @@ import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; import { readStableArtifact } from "../../artifacts/readStableArtifact.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import { + AnalysisAccessDeniedError, AnalysisCancelledError, AnalysisInputError, } from "../../domain/analysisErrorCore.js"; @@ -15,6 +16,8 @@ export interface WebArtifactReadContext { readonly operation: "trace_web_module_imports" | "trace_web_source_location"; readonly field: readonly (string | number)[]; readonly targetPath: string; + /** Whether the caller named this file, rather than a manifest deriving it. */ + readonly callerSelected: boolean; } /** A malformed producer document, distinct from host I/O failures. */ @@ -54,6 +57,10 @@ export const webArtifactReadError = ( ): AnalysisError => { if (signal?.aborted === true) return new AnalysisCancelledError(context.operation); + const selection = context.callerSelected + ? selectedFileError(cause, context) + : undefined; + if (selection !== undefined) return selection; if (cause instanceof ArtifactReaderFailure) return new ArtifactOperationError( context.operation, @@ -91,3 +98,33 @@ export const webArtifactReadError = ( }, }); }; + +/** + * Report a missing, non-regular or unreadable caller-selected file as the + * caller's selection or a host permission denial, not an artifact fault. + */ +const selectedFileError = ( + cause: unknown, + context: WebArtifactReadContext, +): AnalysisError | undefined => { + const selected = (message: string) => + new AnalysisInputError(context.operation, { cause }, [ + { path: context.field, reason: "invalid_value", message }, + ]); + if (cause instanceof ArtifactReaderFailure) + return cause.reason === "path" ? selected(cause.message) : undefined; + const code = + cause instanceof Error && "code" in cause ? String(cause.code) : ""; + if (code === "EACCES" || code === "EPERM") + return new AnalysisAccessDeniedError( + context.operation, + context.targetPath, + code, + { cause }, + ); + if (code === "ENOENT" || code === "ENOTDIR") + return selected( + `Selected file could not be read (${code}): ${context.targetPath}`, + ); + return undefined; +}; diff --git a/src/browser/assets/WebSourceLocationArtifacts.ts b/src/browser/assets/WebSourceLocationArtifacts.ts index aa286654e..21c483bd8 100644 --- a/src/browser/assets/WebSourceLocationArtifacts.ts +++ b/src/browser/assets/WebSourceLocationArtifacts.ts @@ -48,6 +48,7 @@ export class LocalWebSourceLocationArtifacts implements WebSourceLocationArtifac operation: "trace_web_source_location", field: ["source_map", "path"], targetPath: input.source_map.path, + callerSelected: true, }, options?.signal, ), diff --git a/src/browser/modules/WebModuleArtifacts.ts b/src/browser/modules/WebModuleArtifacts.ts index c8ffb4aee..287e6e8de 100644 --- a/src/browser/modules/WebModuleArtifacts.ts +++ b/src/browser/modules/WebModuleArtifacts.ts @@ -52,6 +52,7 @@ export class LocalWebModuleArtifacts implements WebModuleArtifactPort { operation: "trace_web_module_imports", field: ["import_map", "path"], targetPath: selected.path, + callerSelected: true, }, options?.signal, ), diff --git a/tests/boundary/filesystem/webModuleArtifacts.test.ts b/tests/boundary/filesystem/webModuleArtifacts.test.ts index f7ac99983..62b23432a 100644 --- a/tests/boundary/filesystem/webModuleArtifacts.test.ts +++ b/tests/boundary/filesystem/webModuleArtifacts.test.ts @@ -1,6 +1,14 @@ -import { mkdir, readFile, rename, symlink, writeFile } from "node:fs/promises"; +import { + chmod, + mkdir, + readFile, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; import { dirname, join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, onTestFinished } from "vitest"; import { exportWebScripts } from "../../../src/application/WebScriptExportService.js"; import { LocalWebModuleArtifacts } from "../../../src/browser/modules/WebModuleArtifacts.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; @@ -163,20 +171,86 @@ describe("selected captured module artifact boundary", () => { await writeFile(map, "[]"); expect((await new LocalWebModuleArtifacts().load(input)).ok).toBe(false); }); - it("preserves missing filesystem diagnostics separately from malformed input", async () => { +}); + +describe("caller-selected web module files", () => { + const selectionIssue = (field: readonly string[], message: string) => ({ + code: "invalid_request", + details: { + issues: [ + { + path: field, + reason: "invalid_value", + message: expect.stringContaining(message), + }, + ], + }, + }); + + it("reports a missing or non-file manifest selection as invalid input", async () => { const root = await createTestTempDirectory("rea-module-missing-"); - await mkdir(join(root, "directory")); + const missing = join(root, "missing.json"); + const directory = join(root, "directory"); + await mkdir(directory); + for (const [manifest_path, message] of [ + [missing, `(ENOENT): ${missing}`], + [join(missing, "manifest.json"), "(ENOENT)"], + [directory, `Expected a regular file without a symlink: ${directory}`], + ] as const) { + const response = await new LocalWebModuleArtifacts().load({ + manifest_path, + script_index: 0, + }); + if (response.ok) throw new Error("expected selection failure"); + expect(projectAnalysisError(response.error)).toMatchObject( + selectionIssue(["manifest_path"], message), + ); + } + }); + + it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "reports an unreadable manifest as a host access denial", + async () => { + const { manifestPath } = await fixture(); + await chmod(manifestPath, 0o000); + onTestFinished(() => chmod(manifestPath, 0o600)); + const response = await new LocalWebModuleArtifacts().load({ + manifest_path: manifestPath, + script_index: 0, + }); + if (response.ok) throw new Error("expected access denial"); + expect(projectAnalysisError(response.error)).toMatchObject({ + code: "access_denied", + details: { path: manifestPath, system_code: "EACCES" }, + }); + }, + ); + + it("reports a missing import map selection as invalid input", async () => { + const { root, manifestPath } = await fixture(); + const map = join(root, "missing-import-map.json"); const response = await new LocalWebModuleArtifacts().load({ - manifest_path: join(root, "missing.json"), + manifest_path: manifestPath, + script_index: 0, + import_map: { path: map, base_url: "https://app.test/" }, + }); + if (response.ok) throw new Error("expected missing import map"); + expect(projectAnalysisError(response.error)).toMatchObject( + selectionIssue(["import_map", "path"], `(ENOENT): ${map}`), + ); + }); + + it("keeps a missing manifest-derived source as an artifact fault", async () => { + const { manifestPath, sourcePath } = await fixture(); + await rm(sourcePath); + const response = await new LocalWebModuleArtifacts().load({ + manifest_path: manifestPath, script_index: 0, }); - if (response.ok) throw new Error("expected missing file"); + if (response.ok) throw new Error("expected missing source"); expect(response.error).toMatchObject({ _tag: "ArtifactOperationError", reason: "io", }); - expect(projectAnalysisError(response.error).details?.detail).toContain( - "ENOENT", - ); }); }); diff --git a/tests/boundary/filesystem/webSourceLocationArtifacts.test.ts b/tests/boundary/filesystem/webSourceLocationArtifacts.test.ts index 96aa4657f..c443a88ac 100644 --- a/tests/boundary/filesystem/webSourceLocationArtifacts.test.ts +++ b/tests/boundary/filesystem/webSourceLocationArtifacts.test.ts @@ -56,23 +56,28 @@ it.each(["unavailable", "invalid-utf8", "oversized"])( }); if (response.ok) throw new Error("expected map failure"); const projection = projectAnalysisError(response.error); - if (variant === "invalid-utf8") + if (variant === "oversized") + expect(response.error).toMatchObject({ + _tag: "ArtifactOperationError", + reason: "limit", + detail: expect.stringContaining(path), + }); + else expect(projection).toMatchObject({ code: "invalid_request", details: { issues: [ { path: ["source_map", "path"], - message: expect.stringContaining("UTF-8"), + ...(variant === "unavailable" + ? { reason: "invalid_value" } + : { reason: "invalid_format" }), + message: expect.stringContaining( + variant === "unavailable" ? `(ENOENT): ${path}` : "UTF-8", + ), }, ], }, }); - else - expect(response.error).toMatchObject({ - _tag: "ArtifactOperationError", - reason: variant === "oversized" ? "limit" : "io", - detail: expect.stringContaining(path), - }); }, ); From 6875d4a64c0d77c4f90ebbec36705f191eb7cdc6 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:29:42 -0700 Subject: [PATCH 135/189] fix(cli): accept JSON files for web capture and screenshot comparisons (#1397) compare-web-captures and compare-web-screenshots parsed their arguments as inline JSON only, unlike every other JSON-input command. Screenshot artifacts and scenario captures embed base64 PNG bytes, so a typical viewport screenshot exceeds the command-line length limit (128 KiB per argument on Linux, 1 MiB total on macOS) and could not be compared from the CLI at all, while MCP accepts it. A file path was reported as malformed JSON, and screenshot schema failures returned no issues. Each argument now accepts inline JSON or a JSON file path through parseCliJsonInput; file failures keep its path diagnostics, malformed inline JSON keeps the field issue, and screenshot validation reports projected schema issues. The tests share one CLI JSON process fixture. Co-authored-by: Claude Opus 5.5 --- docs/browser-observation.md | 1 + src/cli/browserAdvancedCommands.ts | 114 +++++++++++----- tests/boundary/cli/browserCli.test.ts | 32 +---- .../cli/browserCompareJsonFiles.test.ts | 125 ++++++++++++++++++ .../browserRedirectShapeCompleteness.test.ts | 29 +--- tests/fixtures/cliJsonProcess.ts | 32 +++++ 6 files changed, 238 insertions(+), 95 deletions(-) create mode 100644 tests/boundary/cli/browserCompareJsonFiles.test.ts create mode 100644 tests/fixtures/cliJsonProcess.ts diff --git a/docs/browser-observation.md b/docs/browser-observation.md index 0cebe1649..35cc1e620 100644 --- a/docs/browser-observation.md +++ b/docs/browser-observation.md @@ -18,6 +18,7 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools - `compare_web_captures` / `rea compare-web-captures` compares passive captures or exact-step-aligned browser scenarios. Scenario results commit reproducible literal normalization and expose alignment failures plus artifact-level action, screenshot, DOM, accessibility, URL, history, storage, and event differences. Missing or truncated evidence is never treated as equivalence. - `capture_web_screenshot` / `rea capture-web-screenshot` returns a content-addressed visible-viewport PNG. - `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services. +- The CLI comparison commands accept each capture, screenshot artifact or normalization policy as inline JSON or a JSON file path. Use files for screenshot artifacts and scenario captures, whose embedded PNG bytes can exceed the host's command-line length limit. - Every surface has equivalent CLI and MCP contracts and returns Evidence provenance. - MCP tools return complete results inline and include the Evidence ID. Session evidence can be exported with `export_evidence_bundle`. diff --git a/src/cli/browserAdvancedCommands.ts b/src/cli/browserAdvancedCommands.ts index 63cbbd756..1eff33f4b 100644 --- a/src/cli/browserAdvancedCommands.ts +++ b/src/cli/browserAdvancedCommands.ts @@ -15,13 +15,14 @@ import { type AnalysisInputIssue, } from "../domain/analysisErrorCore.js"; import { browserCaptureComparisonInputSchema } from "../domain/browserCaptureComparison.js"; +import { projectInputIssues } from "../domain/inputIssueProjection.js"; import { discoverWebMcpToolsInputSchema } from "../domain/webMcpDiscovery.js"; import { captureWebScreenshotInputSchema, compareWebScreenshotsInputSchema, } from "../domain/webScreenshot.js"; import type { JsonValue } from "../domain/jsonValue.js"; -import { safeParseJson } from "../domain/safeJson.js"; +import { parseCliJsonInput } from "../cliJsonInput.js"; import type { Logger } from "pino"; import { CLI_COMMANDS } from "../cliCommandNames.js"; @@ -79,46 +80,39 @@ const registerCaptureDiff = ( description: "Compare two normalized passive captures or recorded browser scenarios", args: z.object({ - beforeJson: z.string().describe("Earlier normalized web capture JSON"), - afterJson: z.string().describe("Later normalized web capture JSON"), + beforeJson: z + .string() + .describe("Earlier normalized web capture JSON or JSON file path"), + afterJson: z + .string() + .describe("Later normalized web capture JSON or JSON file path"), }), options: z.object({ normalizationJson: z .string() .default('{"rules":[]}') .describe( - "Recorded literal normalization policy for browser scenarios", + "Recorded literal normalization policy JSON or JSON file path for browser scenarios", ), }), run: ({ args, options }) => logCliCommand(logger, "compare-web-captures", async () => { - const before = safeParseJson(args.beforeJson); - const after = safeParseJson(args.afterJson); - const normalization = safeParseJson(options.normalizationJson); - if (!before.ok) - return inputError("compare_web_captures", [ - invalidJsonIssue("before"), - ]); - if (!after.ok) - return inputError("compare_web_captures", [ - invalidJsonIssue("after"), - ]); - if (!normalization.ok) - return inputError("compare_web_captures", [ - invalidJsonIssue("normalization"), - ]); + const inputs = await parseJsonArguments("compare_web_captures", { + before: args.beforeJson, + after: args.afterJson, + normalization: options.normalizationJson, + }); + if (!inputs.ok) return inputs.error; + const { before, after, normalization } = inputs.value; const scenarioComparison = browserCaptureComparisonInputSchema.safeParse({ - before_scenario: before.value, - after_scenario: after.value, - normalization: normalization.value, + before_scenario: before, + after_scenario: after, + normalization, }); const parsed = scenarioComparison.success ? scenarioComparison - : browserCaptureComparisonInputSchema.safeParse({ - before: before.value, - after: after.value, - }); + : browserCaptureComparisonInputSchema.safeParse({ before, after }); if (!parsed.success) return inputError("compare_web_captures"); const result = await compareWebCaptureEvidence( new CdpBrowserProvider(), @@ -168,8 +162,12 @@ const registerScreenshotDiff = ( cli.command(CLI_COMMANDS.compareWebScreenshots, { description: "Compare two self-verifying PNG artifact JSON values", args: z.object({ - beforeJson: z.string().describe("Earlier screenshot artifact JSON"), - afterJson: z.string().describe("Later screenshot artifact JSON"), + beforeJson: z + .string() + .describe("Earlier screenshot artifact JSON or JSON file path"), + afterJson: z + .string() + .describe("Later screenshot artifact JSON or JSON file path"), }), options: z.object({ channelThreshold: z @@ -182,12 +180,27 @@ const registerScreenshotDiff = ( }), run: ({ args, options }) => logCliCommand(logger, "compare-web-screenshots", async () => { - const parsed = compareWebScreenshotsInputSchema.safeParse({ - before: parseJson(args.beforeJson), - after: parseJson(args.afterJson), - channel_threshold: options.channelThreshold, + const operation = "compare_web_screenshots"; + const inputs = await parseJsonArguments(operation, { + before: args.beforeJson, + after: args.afterJson, }); - if (!parsed.success) return inputError("compare_web_screenshots"); + if (!inputs.ok) return inputs.error; + const { before, after } = inputs.value; + const input = { + before, + after, + channel_threshold: options.channelThreshold, + }; + const parsed = compareWebScreenshotsInputSchema.safeParse(input); + if (!parsed.success) + return browserCliError( + new AnalysisInputError( + operation, + { cause: parsed.error }, + projectInputIssues(parsed.error.issues, input), + ), + ); const result = await compareWebScreenshotEvidence( new CdpBrowserProvider(), parsed.data, @@ -197,11 +210,40 @@ const registerScreenshotDiff = ( }); }; -const parseJson = (value: string): unknown => { - const parsed = safeParseJson(value); - return parsed.ok ? parsed.value : undefined; +/** + * Parse each named inline JSON argument or local JSON file, like other + * JSON-input commands. Screenshot artifacts and scenario captures embed PNG + * bytes that can exceed the host's command-line length limit. + */ +const parseJsonArguments = async ( + operation: string, + fields: Readonly>, +): Promise< + | { readonly ok: true; readonly value: Readonly> } + | { readonly ok: false; readonly error: JsonValue } +> => { + const values: Record = {}; + for (const [field, value] of Object.entries(fields)) { + const parsed = await parseCliJsonInput(value, operation); + if (!parsed.ok) + return isFileInputFailure(parsed.error) + ? parsed + : { + ok: false, + error: inputError(operation, [invalidJsonIssue(field)]), + }; + values[field] = parsed.value; + } + return { ok: true, value: values }; }; +/** File read and decode failures name the selected path; inline JSON does not. */ +const isFileInputFailure = (error: JsonValue): boolean => + typeof error === "object" && + error !== null && + !Array.isArray(error) && + "input_path" in error; + const invalidJsonIssue = (field: string): AnalysisInputIssue => ({ path: [field], reason: "invalid_format", diff --git a/tests/boundary/cli/browserCli.test.ts b/tests/boundary/cli/browserCli.test.ts index 72c9e851d..bfd167a7e 100644 --- a/tests/boundary/cli/browserCli.test.ts +++ b/tests/boundary/cli/browserCli.test.ts @@ -1,15 +1,12 @@ -import { execFile } from "node:child_process"; -import { promisify } from "node:util"; - import { afterEach, describe, expect, it } from "vitest"; +import { runCliJson as runCli } from "../../fixtures/cliJsonProcess.js"; import { startFakeCdpBrowser, type FakeCdpBrowser, type FakeOptions, } from "../../fixtures/fakeCdpBrowser.js"; -const execute = promisify(execFile); const browsers: FakeCdpBrowser[] = []; const INTEGRATION_TEST_TIMEOUT_MS = 60_000; @@ -288,33 +285,6 @@ describe("browser CLI capture parity", () => { ); }); -const runCli = async ( - arguments_: readonly string[], - environment: NodeJS.ProcessEnv, -): Promise => { - try { - const { stdout } = await execute( - process.execPath, - ["scripts/rea.mjs", ...arguments_], - { - cwd: process.cwd(), - env: environment, - maxBuffer: 16 * 1_024 * 1_024, - }, - ); - return JSON.parse(stdout); - } catch (cause: unknown) { - if ( - typeof cause === "object" && - cause !== null && - "stdout" in cause && - typeof cause.stdout === "string" - ) - return JSON.parse(cause.stdout); - throw cause; - } -}; - const screenshotArtifact = (value: unknown): Record => { if ( !isRecord(value) || diff --git a/tests/boundary/cli/browserCompareJsonFiles.test.ts b/tests/boundary/cli/browserCompareJsonFiles.test.ts new file mode 100644 index 000000000..0f067175f --- /dev/null +++ b/tests/boundary/cli/browserCompareJsonFiles.test.ts @@ -0,0 +1,125 @@ +import { randomBytes } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { crc32, deflateSync } from "node:zlib"; + +import { describe, expect, it } from "vitest"; + +import { createWebScreenshotArtifact } from "../../../src/domain/webScreenshot.js"; +import { runCliJson as runCli } from "../../fixtures/cliJsonProcess.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const INTEGRATION_TEST_TIMEOUT_MS = 60_000; +// Linux limits one argument to 128 KiB and macOS all arguments to 1 MiB. +const COMMAND_LINE_LIMIT_BYTES = 1024 * 1024; + +const pngChunk = (type: string, data: Buffer): Buffer => { + const typed = Buffer.concat([Buffer.from(type, "latin1"), data]); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const checksum = Buffer.alloc(4); + checksum.writeUInt32BE(crc32(typed)); + return Buffer.concat([length, typed, checksum]); +}; + +/** An incompressible RGB PNG whose artifact JSON exceeds command-line limits. */ +const noisePng = (width: number, height: number): Buffer => { + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header.set([8, 2, 0, 0, 0], 8); + const rows = Array.from({ length: height }, () => + Buffer.concat([Buffer.of(0), randomBytes(width * 3)]), + ); + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk("IHDR", header), + pngChunk("IDAT", deflateSync(Buffer.concat(rows))), + pngChunk("IEND", Buffer.alloc(0)), + ]); +}; + +describe("browser comparison JSON file inputs", () => { + it( + "compares screenshot artifacts too large for a command-line argument", + async () => { + const root = await createTestTempDirectory("rea-screenshot-files-"); + const artifact = JSON.stringify( + createWebScreenshotArtifact(noisePng(640, 640)), + ); + expect(Buffer.byteLength(artifact)).toBeGreaterThan( + COMMAND_LINE_LIMIT_BYTES, + ); + const before = join(root, "before.json"); + const after = join(root, "after.json"); + await writeFile(before, artifact); + await writeFile(after, artifact); + + expect( + await runCli(["compare-web-screenshots", before, after, "--json"]), + ).toMatchObject({ + operation: "compare_web_screenshots", + normalized_result: { status: "identical", changed_pixels: 0 }, + }); + }, + INTEGRATION_TEST_TIMEOUT_MS, + ); + + it( + "reports which screenshot artifact failed validation", + async () => { + const root = await createTestTempDirectory("rea-screenshot-invalid-"); + const valid = createWebScreenshotArtifact(noisePng(2, 2)); + const before = join(root, "before.json"); + await writeFile(before, JSON.stringify({ ...valid, bytes: 1 })); + + expect( + await runCli([ + "compare-web-screenshots", + before, + JSON.stringify(valid), + "--json", + ]), + ).toMatchObject({ + error: "Browser observation failed", + code: "invalid_request", + details: { + operation: "compare_web_screenshots", + issues: [ + { + path: ["before"], + message: "Screenshot artifact digest or size mismatch", + }, + ], + }, + }); + }, + INTEGRATION_TEST_TIMEOUT_MS, + ); + + it( + "identifies a missing capture file instead of reporting malformed JSON", + async () => { + const root = await createTestTempDirectory("rea-capture-missing-"); + const missing = join(root, "before.json"); + + expect( + await runCli(["compare-web-captures", missing, "{}", "--json"]), + ).toMatchObject({ + code: "invalid_request", + details: { + operation: "compare_web_captures", + issues: [ + { + reason: "invalid_value", + message: expect.stringContaining(`(ENOENT): ${missing}`), + }, + ], + }, + input_path: missing, + input_reason: "read-failed", + }); + }, + INTEGRATION_TEST_TIMEOUT_MS, + ); +}); diff --git a/tests/boundary/cli/browserRedirectShapeCompleteness.test.ts b/tests/boundary/cli/browserRedirectShapeCompleteness.test.ts index 6608ce08d..6340c5c34 100644 --- a/tests/boundary/cli/browserRedirectShapeCompleteness.test.ts +++ b/tests/boundary/cli/browserRedirectShapeCompleteness.test.ts @@ -1,14 +1,11 @@ -import { execFile } from "node:child_process"; -import { promisify } from "node:util"; - import { afterEach, expect, it } from "vitest"; +import { runCliJson as runCli } from "../../fixtures/cliJsonProcess.js"; import { startFakeCdpBrowser, type FakeCdpBrowser, } from "../../fixtures/fakeCdpBrowser.js"; -const execute = promisify(execFile); const browsers: FakeCdpBrowser[] = []; afterEach(async () => { @@ -79,30 +76,6 @@ it("reports missing JSON shapes only when body shapes are selected", async () => }); }); -const runCli = async (arguments_: readonly string[]): Promise => { - try { - const { stdout } = await execute( - process.execPath, - ["scripts/rea.mjs", ...arguments_], - { - cwd: process.cwd(), - env: process.env, - maxBuffer: 16 * 1_024 * 1_024, - }, - ); - return JSON.parse(stdout); - } catch (cause: unknown) { - if ( - typeof cause === "object" && - cause !== null && - "stdout" in cause && - typeof cause.stdout === "string" - ) - return JSON.parse(cause.stdout); - throw cause; - } -}; - const normalizedResult = (value: unknown): Record => { if (!isRecord(value) || !isRecord(value.normalized_result)) throw new TypeError("Missing CLI normalized result"); diff --git a/tests/fixtures/cliJsonProcess.ts b/tests/fixtures/cliJsonProcess.ts new file mode 100644 index 000000000..c66c82d4e --- /dev/null +++ b/tests/fixtures/cliJsonProcess.ts @@ -0,0 +1,32 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +const execute = promisify(execFile); + +/** Run the built CLI and parse its JSON stdout, including a failing command's. */ +export const runCliJson = async ( + arguments_: readonly string[], + environment: NodeJS.ProcessEnv = process.env, +): Promise => { + try { + const { stdout } = await execute( + process.execPath, + ["scripts/rea.mjs", ...arguments_], + { + cwd: process.cwd(), + env: environment, + maxBuffer: 16 * 1_024 * 1_024, + }, + ); + return JSON.parse(stdout); + } catch (cause: unknown) { + if ( + typeof cause === "object" && + cause !== null && + "stdout" in cause && + typeof cause.stdout === "string" + ) + return JSON.parse(cause.stdout); + throw cause; + } +}; From 499e2f54efc65aff427978613284c3e429398d44 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:52:54 -0700 Subject: [PATCH 136/189] perf(evidence): stop copying normalized results into raw_result (#1402) createAnalysisExecution defaulted an omitted rawResult to a second complete copy of the result. Every caller that had no distinct provider representation therefore doubled its Evidence: decode_interface_builder, inspect_keyed_archive, inspect_asset_catalog, trace_dylib_resolution, inspect_native_dispatch_metadata, observe_native_calls, observe_native_ui/capture_native_ui_scenario (including screenshots), and small Ghidra/IDA lifecycle records. Sibling operations of the same providers already recorded null. An omitted rawResult now records null. Normalized results are unchanged. MCP responses repeat Evidence in text and structured content, so each response and its share of the 10 MiB transport budget shrink by the same half; e.g. trace_dylib_resolution on a real app bundle drops from 3,217,119 to 1,612,524 bytes per representation. Co-authored-by: Claude Opus 5.5 --- docs/mcp-contracts.md | 4 +++- src/application/AnalysisProvider.test.ts | 22 +++++++++++++++++++ src/application/AnalysisProvider.ts | 10 +++++++-- tests/boundary/cli/dylibResolutionCli.test.ts | 3 +++ .../composition/directAnalysisCleanup.test.ts | 4 ++-- 5 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 src/application/AnalysisProvider.test.ts diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 66487bd01..5eedd9c14 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -198,7 +198,9 @@ Custom clients upgrading from 6.1 should follow the Evidence-producing tools return the complete canonical Evidence record in both text and structured content. Read `structuredContent.normalized_result` for the -operation result and `structuredContent.evidence_id` for its identity. The same +operation result and `structuredContent.evidence_id` for its identity. +`raw_result` holds a provider representation distinct from that result, such +as an upstream tool's original report, and is `null` when there is none. The same record is retained in the session bundle. `analysis_profile` is always present: a concrete profile object or `null`; either value participates in semantic identity. Records omitting this field are rejected. Pass the returned Evidence diff --git a/src/application/AnalysisProvider.test.ts b/src/application/AnalysisProvider.test.ts new file mode 100644 index 000000000..01b6afc17 --- /dev/null +++ b/src/application/AnalysisProvider.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from "vitest"; + +import { createAnalysisExecution } from "./AnalysisProvider.js"; + +const PROVIDER = { id: "fixture", name: "Fixture", version: "1" }; + +it("records no raw result unless the provider supplies a distinct one", () => { + const result = { entries: [{ value: "normalized" }] }; + + expect(createAnalysisExecution(result, PROVIDER)).toMatchObject({ + result, + rawResult: null, + }); + expect( + createAnalysisExecution(result, PROVIDER, { + rawResult: { stdout: "raw" }, + }).rawResult, + ).toEqual({ stdout: "raw" }); + expect( + createAnalysisExecution(result, PROVIDER, { rawResult: null }).rawResult, + ).toBeNull(); +}); diff --git a/src/application/AnalysisProvider.ts b/src/application/AnalysisProvider.ts index 99328c1a5..a922cdb40 100644 --- a/src/application/AnalysisProvider.ts +++ b/src/application/AnalysisProvider.ts @@ -41,7 +41,13 @@ export interface AnalysisExecution { readonly subject: EvidenceSubjectTarget | null; } -/** Build a validated atomic provider observation at an adapter boundary. */ +/** + * Build a validated atomic provider observation at an adapter boundary. + * + * Pass `rawResult` only for a provider representation distinct from + * `result`. Omitting it records `null` rather than a second complete copy of + * the normalized result in every Evidence record and tool response. + */ export const createAnalysisExecution = ( result: unknown, provider: ProviderIdentity, @@ -56,7 +62,7 @@ export const createAnalysisExecution = ( result: jsonValueSchema.parse(result), rawResult: options.rawResult === undefined - ? jsonValueSchema.parse(result) + ? null : jsonValueSchema.parse(options.rawResult), provider, ...(options.analysisProfile === undefined diff --git a/tests/boundary/cli/dylibResolutionCli.test.ts b/tests/boundary/cli/dylibResolutionCli.test.ts index 7a6b12a4d..c92d265b2 100644 --- a/tests/boundary/cli/dylibResolutionCli.test.ts +++ b/tests/boundary/cli/dylibResolutionCli.test.ts @@ -120,6 +120,9 @@ describe("trace-dylib-resolution CLI", () => { "Contents/Helpers/tool", "Contents/MacOS/App", ]); + // The normalized result is the provider's only representation; Evidence + // must not carry it a second time as raw_result. + expect(result.json).toMatchObject({ raw_result: null }); expect( trace.edges.map(({ loader, install_name: name, resolution }) => [ loader, diff --git a/tests/composition/directAnalysisCleanup.test.ts b/tests/composition/directAnalysisCleanup.test.ts index 22fd84942..fcbdbddcb 100644 --- a/tests/composition/directAnalysisCleanup.test.ts +++ b/tests/composition/directAnalysisCleanup.test.ts @@ -84,7 +84,7 @@ describe("one-shot analysis cleanup outcomes", () => { operation: "read_bytes", subject: { local_path: path }, normalized_result: { observation: "retained result" }, - raw_result: { observation: "retained result" }, + raw_result: null, }, }, }); @@ -198,7 +198,7 @@ describe("managed one-shot cleanup outcomes", () => { operation: "inspect_managed_artifact", observation: "retained result", }, - rawResult: { observation: "retained result" }, + rawResult: null, provider: { id: "fixture" }, }, }, From 7623e21ff02cf4eb00ccb4fa357936e4ed01425e Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:00:11 -0700 Subject: [PATCH 137/189] perf(native): record pwntools diagnostics once in their Evidence (#1404) inspect_binary_layout and inspect_recorded_crash passed the decoded report as both result and rawResult, so every Evidence record carried the whole report twice (and an MCP response four times, counting its text copy). The decoded report is the only representation, so raw_result is now null, as for other single-representation operations. The real pwntools verifiers asserted the duplicate; they now assert null. Co-authored-by: Claude Opus 5.5 --- scripts/verify-binary-layout.mjs | 2 +- scripts/verify/recorded-crash/public.mjs | 2 +- .../binaryDiagnostics/BinaryLayoutService.test.ts | 14 ++++++++++++++ .../binaryDiagnostics/BinaryLayoutService.ts | 3 ++- .../binaryDiagnostics/RecordedCrashService.test.ts | 1 + .../binaryDiagnostics/RecordedCrashService.ts | 3 ++- tests/fixtures/analysisView.ts | 2 +- 7 files changed, 22 insertions(+), 5 deletions(-) diff --git a/scripts/verify-binary-layout.mjs b/scripts/verify-binary-layout.mjs index 996eb3966..1f3b5e4bc 100644 --- a/scripts/verify-binary-layout.mjs +++ b/scripts/verify-binary-layout.mjs @@ -1283,7 +1283,7 @@ async function inspect( evidence.provider.version, "pwntools@4.15.0;pyelftools@0.33;unicorn@2.1.2", ); - assert.deepEqual(evidence.normalized_result, evidence.raw_result); + assert.equal(evidence.raw_result, null); assert.equal(evidence.normalized_result.diagnostics.truncated, false); return evidence.normalized_result; } diff --git a/scripts/verify/recorded-crash/public.mjs b/scripts/verify/recorded-crash/public.mjs index 76713bf9f..ecdfd14cd 100644 --- a/scripts/verify/recorded-crash/public.mjs +++ b/scripts/verify/recorded-crash/public.mjs @@ -80,7 +80,7 @@ export async function connectRecordedCrash({ entrypoint, environment }) { evidence.confidence, debuggerContext ? "derived" : "observed", ); - assert.deepEqual(evidence.raw_result, report); + assert.equal(evidence.raw_result, null); assert.equal(evidence.subject.local_path, path); assert.equal(report.artifact.path, path); assert.equal( diff --git a/src/application/binaryDiagnostics/BinaryLayoutService.test.ts b/src/application/binaryDiagnostics/BinaryLayoutService.test.ts index e8f3e2c6d..e65da65f6 100644 --- a/src/application/binaryDiagnostics/BinaryLayoutService.test.ts +++ b/src/application/binaryDiagnostics/BinaryLayoutService.test.ts @@ -5,6 +5,7 @@ import { BINARY_LAYOUT_TEST_PROVIDER, } from "../../../tests/fixtures/binaryDiagnostics/layout.js"; import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js"; +import { parseEvidence } from "../../domain/evidence.js"; import { err, ok } from "../../domain/result.js"; it.each([ @@ -28,6 +29,19 @@ it.each([ }, ); +it("records the decoded layout once in its Evidence", async () => { + const layout = binaryLayoutFixture(); + const service = new BinaryLayoutService({ + identity: BINARY_LAYOUT_TEST_PROVIDER, + inspect: () => Promise.resolve(ok(layout)), + }); + const result = await service.inspect({ path: layout.artifact.path }); + if (!result.ok) throw result.error; + const evidence = parseEvidence(result.value); + expect(evidence.normalized_result).toEqual(layout); + expect(evidence.raw_result).toBeNull(); +}); + it("preserves a provider's actionable unsupported reason", async () => { const failure = new AnalysisCapabilityUnavailableError( "fixture-layout", diff --git a/src/application/binaryDiagnostics/BinaryLayoutService.ts b/src/application/binaryDiagnostics/BinaryLayoutService.ts index 11bfeb76e..bdb07da56 100644 --- a/src/application/binaryDiagnostics/BinaryLayoutService.ts +++ b/src/application/binaryDiagnostics/BinaryLayoutService.ts @@ -78,7 +78,8 @@ export class BinaryLayoutService { operation: OPERATION, parameters: input.data, result: value, - rawResult: value, + // The decoded report is the only representation; do not repeat it. + rawResult: null, confidence: "observed", limitations: value.limitations, locations: [{ kind: "artifact-path", path: value.artifact.path }], diff --git a/src/application/binaryDiagnostics/RecordedCrashService.test.ts b/src/application/binaryDiagnostics/RecordedCrashService.test.ts index 6060aef33..0ab49ee1b 100644 --- a/src/application/binaryDiagnostics/RecordedCrashService.test.ts +++ b/src/application/binaryDiagnostics/RecordedCrashService.test.ts @@ -24,6 +24,7 @@ it("labels an envelope containing debugger-derived maps as derived", async () => const evidence = parseEvidence(result.value); expect(evidence.confidence).toBe("derived"); expect(evidence.normalized_result).toEqual(fixture); + expect(evidence.raw_result).toBeNull(); }); it.each([ diff --git a/src/application/binaryDiagnostics/RecordedCrashService.ts b/src/application/binaryDiagnostics/RecordedCrashService.ts index cfc9278dc..5a4fff645 100644 --- a/src/application/binaryDiagnostics/RecordedCrashService.ts +++ b/src/application/binaryDiagnostics/RecordedCrashService.ts @@ -83,7 +83,8 @@ export class RecordedCrashService { operation: OPERATION, parameters: input.data, result: value, - rawResult: value, + // The decoded report is the only representation; do not repeat it. + rawResult: null, confidence: value.debugger.status === "available" ? "derived" : "observed", limitations: value.limitations, diff --git a/tests/fixtures/analysisView.ts b/tests/fixtures/analysisView.ts index 0f928a22a..d3be2b1e3 100644 --- a/tests/fixtures/analysisView.ts +++ b/tests/fixtures/analysisView.ts @@ -99,7 +99,7 @@ export const analysisViewLayoutEvidence = ( operation: "inspect_binary_layout", parameters: { path: layout.artifact.path }, result: layout, - rawResult: layout, + rawResult: null, confidence: "observed", limitations: layout.limitations, locations: [{ kind: "artifact-path", path: layout.artifact.path }], From 1f0f728c63a4d9f32fc183c6a41627eedb8d1fe2 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:00:35 -0700 Subject: [PATCH 138/189] perf(hopper): stop repeating Hopper replies as raw_result (#1405) HopperProvider passed the bridge reply as rawResult and, for every operation except address_to_file_offset, the same object as the result. Every Hopper Evidence record (decompilation, procedure and string listings, xrefs, ...) therefore carried its complete result twice, and an MCP response four times counting its text copy. raw_result is now null unless REA transformed the reply, which only the file-offset mapping does; that case keeps Hopper's original reply. Co-authored-by: Claude Opus 5.5 --- src/hopper/HopperProvider.ts | 3 ++- tests/acceptance/applications/runtime.test.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index 5b1da0ba9..6c314ddb6 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -249,7 +249,8 @@ export class HopperProvider implements AnalysisProviderCandidate { ? { ok: true, value: createAnalysisExecution(mapped.value, executionProvider, { - rawResult: result.value, + // Only the file-offset mapping differs from Hopper's reply. + rawResult: mapped === result ? null : result.value, ...(profile === undefined ? {} : { analysisProfile: profile }), limitations: [ ...(preparedImage === undefined diff --git a/tests/acceptance/applications/runtime.test.ts b/tests/acceptance/applications/runtime.test.ts index 1a50c3fc1..bfa75b721 100644 --- a/tests/acceptance/applications/runtime.test.ts +++ b/tests/acceptance/applications/runtime.test.ts @@ -144,6 +144,8 @@ describe("production stdio runtime", () => { expect(evidence.operation).toBe("current_document"); expect(evidence.provider.id).toBe("hopper"); expect(evidence.normalized_result).toBe(observation.normalized_result); + // Hopper's reply is the result; it is not repeated as raw_result. + expect(evidence.raw_result).toBeNull(); expect(records).toContainEqual( expect.objectContaining({ application: "rea", From 8550913cda311e5340cf012b9c4afd622e36e35b Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:00:53 +0800 Subject: [PATCH 139/189] fix(javascript)!: stop copying literals into semantic metadata (#1407) Commit literal values with canonical JSON SHA-256 in semantic role keys and use a type label for strings. Preserve complete values, provenance and literal queries while avoiding two payload copies in each string node. Verify real compiled CLI/default stdio MCP, typed union seeds, empty strings and trace continuation with a large source-owned fixture. Refs #723 BREAKING CHANGE: Newly produced semantic literal node IDs use value-sha256 role keys, and string labels read "string literal". Read exact values from properties.value and obtain node IDs from the selected parent graph. Previously stored Evidence and its original IDs remain valid. --- docs/javascript-application-workflows.md | 12 ++ .../JavaScriptSemanticGraphValueProjection.ts | 7 +- .../mcp/javascriptLiteralPayload.test.ts | 154 ++++++++++++++++++ 3 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 tests/boundary/mcp/javascriptLiteralPayload.test.ts diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index cb3e1e5e9..c25746416 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -90,6 +90,18 @@ keep the result ambiguous. Runtime Evidence can later corroborate an exact mapped candidate, but structural reachability, semantic influence, runtime observation, and causal proof remain separate claims. +Semantic literal nodes keep their complete value in `properties.value`; literal +queries match that field. String labels read `string literal` rather than +repeating the payload. A literal's `identity.role_key` commits its canonical +JSON value as `value-sha256:`, together with its binding and property +role. This keeps large values out of identity and display metadata without +truncating their Evidence. + +New analyses therefore produce different literal node IDs from the earlier +payload-bearing role keys. Use IDs returned by the selected parent graph and +read literal values from `properties.value`, rather than decoding role keys or +labels. Previously stored graphs and their original IDs remain valid inputs. + ## Version comparison REA pairs entities only when a tier produces one unique candidate on each side. diff --git a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts index b8002fcd0..dfe8267b6 100644 --- a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts @@ -2,6 +2,7 @@ import { semanticContainer, semanticPropertyPointer, } from "../../domain/javascript/javascriptSemanticSlots.js"; +import { digestCanonicalValue } from "../../domain/canonicalDigest.js"; import type { JavaScriptSemanticBinding } from "../../domain/javascript/javascriptSemanticIr.js"; import type { JavaScriptSemanticProperty, @@ -156,9 +157,11 @@ const addLiteralNode = ( ) => retainSemanticGraphNode(context.state, context.file, { kind: "literal", - roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`, + // Identity needs an exact value commitment, not another payload copy. + // Keep the complete literal in properties for queries and Evidence export. + roleKey: `literal:${binding.bindingId}:${role}:value-sha256:${digestCanonicalValue(value, "Semantic literal")}`, location: binding.definitions[0]?.location ?? null, - label: JSON.stringify(value), + label: typeof value === "string" ? "string literal" : JSON.stringify(value), functionNodeId: context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null, properties: { value }, diff --git a/tests/boundary/mcp/javascriptLiteralPayload.test.ts b/tests/boundary/mcp/javascriptLiteralPayload.test.ts new file mode 100644 index 000000000..b7fcbb876 --- /dev/null +++ b/tests/boundary/mcp/javascriptLiteralPayload.test.ts @@ -0,0 +1,154 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { createHash } from "node:crypto"; +import { 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 { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +cliTest( + "delivers complete large literals through CLI and default stdio MCP without metadata copies", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-literal-payload-"); + const value = 'rea_literal_payload_ğ\\"\0'.padEnd(24, "x").repeat(65_536); + const source = [ + `export const payload = ${JSON.stringify(value)};`, + 'export const choice = flag ? 1 : "1";', + 'export const empty = "";', + ].join("\n"); + await writeFile(join(root, "main.js"), source); + const cliResponse = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + timeoutMs: 60_000, + }); + expect(cliResponse.exitCode).toBe(0); + const cliEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(cliResponse.json); + + const client = new Client({ name: "literal-payload-e2e", 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 response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + // The old payload-bearing role key/label exceed the default wire budget. + expect(response.isError).not.toBe(true); + const evidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(response.structuredContent); + expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); + const text = response.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + const textEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(JSON.parse(text.text)); + expect(textEvidence.evidence_id).toBe(evidence.evidence_id); + const graph = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ).semantic_graph; + const literal = graph.nodes.find( + (node) => node.kind === "literal" && node.properties.value === value, + ); + if (literal === undefined) throw new Error("Complete literal was lost"); + const sourceSha256 = createHash("sha256").update(source).digest("hex"); + expect(literal.identity).toMatchObject({ + module_path: "main.js", + artifact_sha256: sourceSha256, + }); + expect(literal.evidence.location).toMatchObject({ + available: true, + value: { kind: "source-range", source: "main.js" }, + }); + const choices = graph.nodes.filter( + (node) => + node.kind === "literal" && + (node.properties.value === 1 || node.properties.value === "1"), + ); + expect(choices.length).toBe(2); + expect(new Set(choices.map((node) => node.node_id)).size).toBe(2); + expect( + graph.nodes.some( + (node) => node.kind === "literal" && node.properties.value === "", + ), + ).toBe(true); + + const traceResponse = await client.callTool({ + name: "trace_javascript_semantics", + arguments: { + application: { + kind: "retained-evidence", + evidence_id: evidence.evidence_id, + }, + query: { + seed: { kind: "semantic-node", node_id: literal.node_id }, + direction: "backward-provenance", + }, + }, + }); + expect(traceResponse.isError).not.toBe(true); + const traceEvidence = toolContract( + "trace_javascript_semantics", + ).outputSchema.parse(traceResponse.structuredContent); + const trace = javaScriptSemanticTraceResultSchema.parse( + traceEvidence.normalized_result, + ); + expect( + trace.nodes.some( + (node) => + node.node_id === literal.node_id && node.properties.value === value, + ), + ).toBe(true); + const valueTraceResponse = await client.callTool({ + name: "trace_javascript_semantics", + arguments: { + application: { + kind: "retained-evidence", + evidence_id: evidence.evidence_id, + }, + query: { + seed: { kind: "literal", value: "1" }, + direction: "backward-provenance", + }, + }, + }); + expect(valueTraceResponse.isError).not.toBe(true); + const valueTraceEvidence = toolContract( + "trace_javascript_semantics", + ).outputSchema.parse(valueTraceResponse.structuredContent); + const valueTrace = javaScriptSemanticTraceResultSchema.parse( + valueTraceEvidence.normalized_result, + ); + expect(valueTrace.seed_node_ids).toEqual( + choices + .filter((node) => node.properties.value === "1") + .map((node) => node.node_id), + ); + await client.ping(); + } finally { + await client.close(); + await transport.close(); + } + }, + 60_000, +); From de8fc6719596305b1d76204e6b052cf46d7e7fc3 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:23:47 +0800 Subject: [PATCH 140/189] fix(javascript): retain shorter literal metadata encodings (#1408) Choose the shorter complete JSON or digest key and string display label. Short values keep their existing identities and labels, while large values retain the payload-copy reduction without an arbitrary truncation limit. --- docs/javascript-application-workflows.md | 18 ++++++++++-------- .../JavaScriptSemanticGraphValueProjection.ts | 17 +++++++++++++---- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index c25746416..009371035 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -91,16 +91,18 @@ mapped candidate, but structural reachability, semantic influence, runtime observation, and causal proof remain separate claims. Semantic literal nodes keep their complete value in `properties.value`; literal -queries match that field. String labels read `string literal` rather than -repeating the payload. A literal's `identity.role_key` commits its canonical -JSON value as `value-sha256:`, together with its binding and property -role. This keeps large values out of identity and display metadata without +queries match that field. String labels use `string literal` when that is +shorter than the complete JSON value. A literal's `identity.role_key` commits +its canonical JSON value as `value-sha256:` when the digest key is +shorter; smaller values keep their existing JSON key. This keeps large values +out of identity and display metadata without expanding short values or truncating their Evidence. -New analyses therefore produce different literal node IDs from the earlier -payload-bearing role keys. Use IDs returned by the selected parent graph and -read literal values from `properties.value`, rather than decoding role keys or -labels. Previously stored graphs and their original IDs remain valid inputs. +New analyses therefore produce different IDs for hashed literals from the +earlier payload-bearing role keys. Use IDs returned by the selected parent +graph and read literal values from `properties.value`, rather than decoding +role keys or labels. Previously stored graphs and their original IDs remain +valid inputs. ## Version comparison diff --git a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts index dfe8267b6..febe23d24 100644 --- a/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphValueProjection.ts @@ -154,18 +154,27 @@ const addLiteralNode = ( binding: JavaScriptSemanticBinding, value: string | number | boolean | null, role: string, -) => - retainSemanticGraphNode(context.state, context.file, { +) => { + const encodedValue = JSON.stringify(value); + const valueDigest = `value-sha256:${digestCanonicalValue(value, "Semantic literal")}`; + const valueKey = + encodedValue.length <= valueDigest.length ? encodedValue : valueDigest; + const stringLabel = "string literal"; + return retainSemanticGraphNode(context.state, context.file, { kind: "literal", // Identity needs an exact value commitment, not another payload copy. // Keep the complete literal in properties for queries and Evidence export. - roleKey: `literal:${binding.bindingId}:${role}:value-sha256:${digestCanonicalValue(value, "Semantic literal")}`, + roleKey: `literal:${binding.bindingId}:${role}:${valueKey}`, location: binding.definitions[0]?.location ?? null, - label: typeof value === "string" ? "string literal" : JSON.stringify(value), + label: + typeof value === "string" && encodedValue.length > stringLabel.length + ? stringLabel + : encodedValue, functionNodeId: context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null, properties: { value }, }); +}; /** Create one canonical slot for a root binding and exact static property path. */ export const semanticPropertySlot = ( From ca3131b36ccf025f64b9e43ecae2698d37747de7 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:29:48 -0700 Subject: [PATCH 141/189] perf(cli): write compact JSON when output is not a terminal (#1413) `--json` / `--format json` always indented its streamed result. Agents and scripts read REA through pipes and redirects, where indentation carries no information: on real application results it added 16-45% model tokens (o200k proxy) and 25-73% bytes. The skill's CLI fallback uses `--json`. Indent only when stdout is a TTY, as `gh --json` does; piped or redirected JSON is compact. The JSON value, `jsonl`, `--filter-output`, `--full-output` and the token-window paths are unchanged. `jq .` restores indentation for files. Co-authored-by: Claude Opus 5.5 --- docs/cli.md | 5 +++- scripts/verify/javascript/output.mjs | 6 ++-- src/cli/jsonOutput.ts | 18 ++++++++++-- .../tools/historicalCaptureResources.test.ts | 28 +++++++++++-------- tests/boundary/cli/jsonOutput.test.ts | 15 ++++++++++ 5 files changed, 53 insertions(+), 19 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index ed5f810e9..2a9863c1e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -179,7 +179,10 @@ user permissions; consult the chosen guide for host requirements and effects. ## Output and exit status The default terminal format is TOON. Use `--json` when saving results for a -JSON consumer. Output selection and formatting do not change operation status. +JSON consumer. `--json` is indented on a terminal and compact when piped or +redirected, which keeps large results smaller for agents and scripts; pipe +through `jq .` for indented files. Output selection and formatting do not change +operation status. | Status | Meaning | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/scripts/verify/javascript/output.mjs b/scripts/verify/javascript/output.mjs index 13dfa916c..dbdfdc340 100644 --- a/scripts/verify/javascript/output.mjs +++ b/scripts/verify/javascript/output.mjs @@ -54,15 +54,15 @@ try { data: { ...evidence, normalized_result: { payload: [marker] } }, meta: metadata, }; - const skeleton = JSON.stringify(template, null, format === "json" ? 2 : 0); + // The destination is a redirected file, so both formats are compact. + const skeleton = JSON.stringify(template); const encodedMarker = JSON.stringify(marker); const markerIndex = skeleton.indexOf(encodedMarker); assert.ok(markerIndex >= 0); assert.equal(markerIndex, skeleton.lastIndexOf(encodedMarker)); const prefix = skeleton.slice(0, markerIndex); const suffix = `${skeleton.slice(markerIndex + encodedMarker.length)}\n`; - const indentation = prefix.slice(prefix.lastIndexOf("\n") + 1); - const separator = format === "json" ? `,\n${indentation}` : ","; + const separator = ","; const expectedHash = createHash("sha256"); expectedHash.update(prefix); for (let index = 0; index < count; index += 1) { diff --git a/src/cli/jsonOutput.ts b/src/cli/jsonOutput.ts index b42bd82bd..f7422a7bf 100644 --- a/src/cli/jsonOutput.ts +++ b/src/cli/jsonOutput.ts @@ -4,16 +4,27 @@ import { bufferedJsonParts, jsonParts } from "../domain/jsonSerialization.js"; type JsonOutputFormat = "json" | "jsonl"; -/** Write ordinary JSON without constructing a document-sized string. */ +/** + * Write ordinary JSON without constructing a document-sized string. + * + * `json` is indented for a terminal reader. Piped or redirected output, which + * agents and scripts consume, is compact: indentation adds no information and + * measured 16-45% more model tokens on real results. The value is identical. + */ export const writeJsonOutput = async ( value: unknown, destination: Writable, format: JsonOutputFormat = "json", ): Promise => { - for (const part of bufferedJsonParts(jsonOutputParts(value, format))) + for (const part of bufferedJsonParts( + jsonOutputParts(value, format, isTerminal(destination)), + )) await writePart(destination, part); }; +const isTerminal = (destination: Writable): boolean => + "isTTY" in destination && destination.isTTY === true; + const writePart = (destination: Writable, part: string): Promise => new Promise((resolve, reject) => { const onError = (cause: unknown): void => reject(cause); @@ -39,6 +50,7 @@ const writePart = (destination: Writable, part: string): Promise => export function* jsonOutputParts( value: unknown, format: JsonOutputFormat, + pretty = true, ): Generator { if (format === "jsonl" && Array.isArray(value)) { for (const item of value) { @@ -47,6 +59,6 @@ export function* jsonOutputParts( } return; } - yield* jsonParts(value, format === "json"); + yield* jsonParts(value, pretty && format === "json"); yield "\n"; } diff --git a/tests/acceptance/tools/historicalCaptureResources.test.ts b/tests/acceptance/tools/historicalCaptureResources.test.ts index 7aea0fcce..87e509e65 100644 --- a/tests/acceptance/tools/historicalCaptureResources.test.ts +++ b/tests/acceptance/tools/historicalCaptureResources.test.ts @@ -83,18 +83,22 @@ it("reports real HAR heap exhaustion through CLI and MCP and preserves server us }); expect(JSON.stringify(response)).not.toContain("caller-marked"); expect(JSON.stringify(response)).not.toContain("rea doctor"); - await expect( - execute(process.execPath, [ - cli, - "inspect-web-network-capture", - path, - "har", - "--json", - ]), - ).rejects.toMatchObject({ - code: 1, - stdout: expect.stringContaining('"code": "resource_constraint"'), - }); + const failed: unknown = await execute(process.execPath, [ + cli, + "inspect-web-network-capture", + path, + "har", + "--json", + ]).then( + () => undefined, + (cause: unknown) => cause, + ); + expect(failed).toMatchObject({ code: 1 }); + const stdout = + typeof failed === "object" && failed !== null && "stdout" in failed + ? String(failed.stdout) + : ""; + expect(JSON.parse(stdout)).toMatchObject({ code: "resource_constraint" }); const small = join(root, "small.har"); await writeFile(small, capture(2)); await client.ping(); diff --git a/tests/boundary/cli/jsonOutput.test.ts b/tests/boundary/cli/jsonOutput.test.ts index 029407388..fd03f0e92 100644 --- a/tests/boundary/cli/jsonOutput.test.ts +++ b/tests/boundary/cli/jsonOutput.test.ts @@ -16,6 +16,7 @@ import { silentLogger } from "../../../src/logger.js"; const collect = async ( value: unknown, format: "json" | "jsonl" = "json", + terminal = true, ): Promise => { const chunks: Buffer[] = []; const destination = new Writable({ @@ -28,6 +29,7 @@ const collect = async ( callback(); }, }); + if (terminal) Object.defineProperty(destination, "isTTY", { value: true }); await writeJsonOutput(value, destination, format); return Buffer.concat(chunks).toString("utf8"); }; @@ -52,6 +54,16 @@ describe("incremental CLI JSON", () => { expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`); }); + it("indents JSON only for a terminal and writes piped JSON compactly", async () => { + const value = { nested: [{ value: null }], text: "雪𝟠" }; + expect(await collect(value, "json", true)).toBe( + `${JSON.stringify(value, null, 2)}\n`, + ); + expect(await collect(value, "json", false)).toBe( + `${JSON.stringify(value)}\n`, + ); + }); + it("writes compact JSONL records and preserves an empty record set", async () => { const value = [{ text: "first\nrecord" }, { text: "雪𝟠" }]; expect(await collect(value, "jsonl")).toBe( @@ -78,6 +90,7 @@ describe("incremental CLI JSON", () => { }, 1); }, }); + Object.defineProperty(destination, "isTTY", { value: true }); await writeJsonOutput({ leaf }, destination); expect(largestChunk).toBeLessThan(Buffer.byteLength(leaf)); const actual = Buffer.concat(chunks).toString("utf8"); @@ -212,6 +225,8 @@ describe("streamed CLI result surface", () => { expect(operation).toBe("inspect_managed_members"); return value; }); + // A terminal destination exercises the indented encoding past the limit. + Object.defineProperty(destination, "isTTY", { value: true }); const argv = ["inspect-managed-members", "fixture.dll", "--json"]; const output = createStreamedCliJsonOutput(argv, destination); if (output === undefined) throw new Error("Missing JSON output surface"); From 4d8ef3f35022f286e5a6b2ee250cfb336e14a4ad Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:30:42 +0800 Subject: [PATCH 142/189] perf(javascript): aggregate semantic family coverage once (#1410) Reduce repeated semantic relation and unknown family scans while preserving exact complete Evidence and coverage. --- .../JavaScriptSemanticGraphBuilder.ts | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts index a951a7a55..45ded5051 100644 --- a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts +++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts @@ -175,7 +175,21 @@ export const createJavaScriptSemanticGraphProjection = ): Value => { bindSemanticGraphApplicationNodes(state, applicationGraph); if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state); + const relations = [...state.relations.values()]; const unknowns = [...state.unknowns.values()]; + type Family = (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number]; + const retainedByFamily = new Map(); + const unknownIdsByFamily = new Map(); + for (const relation of relations) { + const family = JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation]; + retainedByFamily.set(family, (retainedByFamily.get(family) ?? 0) + 1); + } + for (const unknown of unknowns) { + const identifiers = unknownIdsByFamily.get(unknown.family); + if (identifiers === undefined) + unknownIdsByFamily.set(unknown.family, [unknown.unknown_id]); + else identifiers.push(unknown.unknown_id); + } const graph = factory({ schema: "JavaScriptSemanticRelationGraph", root_artifact_sha256: rootArtifactSha256, @@ -183,7 +197,7 @@ export const createJavaScriptSemanticGraphProjection = root_node_ids: [...state.roots], evidence_contexts: state.evidenceContexts.contexts, nodes: [...state.nodes.values()], - relations: [...state.relations.values()], + relations, fingerprints, unknowns, coverage: { @@ -204,15 +218,9 @@ export const createJavaScriptSemanticGraphProjection = families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({ family, status: semanticFamilyStatus(family), - retained_relations: [...state.relations.values()].filter( - (relation) => - JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] === - family, - ).length, + retained_relations: retainedByFamily.get(family) ?? 0, omitted_relations: truncatedFiles > 0 ? null : 0, - unknown_ids: unknowns - .filter((unknown) => unknown.family === family) - .map(({ unknown_id: identifier }) => identifier), + unknown_ids: unknownIdsByFamily.get(family) ?? [], })), }, limitations: [ From 81cdafc132c7ba3bd6e12b1169f9e3687025d07b Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:45:42 +0800 Subject: [PATCH 143/189] =?UTF-8?q?docs:=20celebrate=2050,000=20GitHub=20s?= =?UTF-8?q?tars=20=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- README_ar.md | 2 +- README_de.md | 2 +- README_es.md | 2 +- README_fa.md | 2 +- README_fr.md | 2 +- README_ja.md | 2 +- README_ko.md | 2 +- README_pl.md | 2 +- README_pt-BR.md | 2 +- README_ru.md | 2 +- README_th.md | 2 +- README_tr.md | 2 +- README_uk.md | 2 +- README_vi.md | 2 +- README_zh-TW.md | 2 +- README_zh.md | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 7509d81ea..e345a56f1 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,7 @@ Report vulnerabilities through [SECURITY.md](SECURITY.md). ## Star history -🎉 **40,000 GitHub stars — thank you!** +🎉 **50,000 GitHub stars — thank you!** Thanks to everyone using REA, reporting bugs, requesting features, testing builds, and contributing fixes. diff --git a/README_ar.md b/README_ar.md index 92151b9c7..43bb3adc9 100644 --- a/README_ar.md +++ b/README_ar.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## سجل النجوم -🎉 **40,000 نجمة على GitHub — شكرًا لكم!** +🎉 **50,000 نجمة على GitHub — شكرًا لكم!** شكرًا لكل من يستخدم REA، ويبلّغ عن الأخطاء، ويقترح ميزات، ويختبر إصدارات البناء، ويساهم بالإصلاحات. diff --git a/README_de.md b/README_de.md index b71795bc0..776aa649d 100644 --- a/README_de.md +++ b/README_de.md @@ -256,7 +256,7 @@ Melde Sicherheitslücken gemäß [SECURITY.md](SECURITY.md). ## Sternverlauf -🎉 **40.000 GitHub-Sterne – vielen Dank!** +🎉 **50.000 GitHub-Sterne – vielen Dank!** Danke an alle, die REA nutzen, Fehler melden, Funktionswünsche äußern, Builds testen und Fehlerbehebungen beitragen. diff --git a/README_es.md b/README_es.md index ac86b1f4d..1dafea412 100644 --- a/README_es.md +++ b/README_es.md @@ -256,7 +256,7 @@ Informa de vulnerabilidades siguiendo [SECURITY.md](SECURITY.md). ## Historial de estrellas -🎉 **40.000 estrellas en GitHub: ¡gracias!** +🎉 **50.000 estrellas en GitHub: ¡gracias!** Gracias a quienes usan REA, informan de errores, solicitan funciones, prueban compilaciones y contribuyen con correcciones. diff --git a/README_fa.md b/README_fa.md index 7b2b307d9..f7c70ca1d 100644 --- a/README_fa.md +++ b/README_fa.md @@ -241,7 +241,7 @@ npx rea-agents@latest setup ## تاریخچهٔ ستاره‌ها -🎉 **۴۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** +🎉 **۵۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** از همهٔ کسانی که از REA استفاده می‌کنند، خطاها را گزارش می‌دهند، قابلیت‌های جدید پیشنهاد می‌کنند، buildها را آزمایش می‌کنند و در بهبود پروژه مشارکت دارند سپاسگزاریم. diff --git a/README_fr.md b/README_fr.md index 8fa07803b..00f22dfd9 100644 --- a/README_fr.md +++ b/README_fr.md @@ -257,7 +257,7 @@ Signalez les vulnérabilités via [SECURITY.md](SECURITY.md). ## Historique des étoiles -🎉 **40 000 étoiles GitHub — merci !** +🎉 **50 000 étoiles GitHub — merci !** Merci à toutes les personnes qui utilisent REA, signalent des bugs, proposent des fonctionnalités, testent les builds et contribuent des correctifs. diff --git a/README_ja.md b/README_ja.md index b827c3c04..c100c1f16 100644 --- a/README_ja.md +++ b/README_ja.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## スター履歴 -🎉 **GitHub スター 40,000 件、ありがとうございます!** +🎉 **GitHub スター 50,000 件、ありがとうございます!** REA の利用、バグ報告、機能の要望、ビルドのテスト、修正への貢献に感謝します。 diff --git a/README_ko.md b/README_ko.md index 876792059..9dda2ee1b 100644 --- a/README_ko.md +++ b/README_ko.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## 스타 기록 -🎉 **GitHub 스타 40,000개, 감사합니다!** +🎉 **GitHub 스타 50,000개, 감사합니다!** REA를 사용하고, 버그를 보고하고, 기능을 요청하고, 빌드를 테스트하고, 수정에 기여해 주신 모든 분께 감사드립니다. diff --git a/README_pl.md b/README_pl.md index bdd062da9..f234fe034 100644 --- a/README_pl.md +++ b/README_pl.md @@ -256,7 +256,7 @@ Zgłaszaj podatności zgodnie z [SECURITY.md](SECURITY.md). ## Historia gwiazdek -🎉 **40 000 gwiazdek na GitHubie — dziękujemy!** +🎉 **50 000 gwiazdek na GitHubie — dziękujemy!** Dziękujemy wszystkim, którzy używają REA, zgłaszają błędy, proponują nowe funkcje, testują kompilacje i przesyłają poprawki. diff --git a/README_pt-BR.md b/README_pt-BR.md index 711f7d788..a788e2985 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -256,7 +256,7 @@ Relate vulnerabilidades conforme [SECURITY.md](SECURITY.md). ## Histórico de estrelas -🎉 **40.000 estrelas no GitHub — muito obrigado!** +🎉 **50.000 estrelas no GitHub — muito obrigado!** Obrigado a todos que usam o REA, relatam bugs, sugerem funcionalidades, testam builds e contribuem com correções. diff --git a/README_ru.md b/README_ru.md index 6b44940e9..cc845a622 100644 --- a/README_ru.md +++ b/README_ru.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## История звёзд -🎉 **40 000 звёзд на GitHub — спасибо!** +🎉 **50 000 звёзд на GitHub — спасибо!** Спасибо всем, кто использует REA, сообщает об ошибках, предлагает новые функции, тестирует сборки и помогает с исправлениями. diff --git a/README_th.md b/README_th.md index c66e1a393..2dd8b83e5 100644 --- a/README_th.md +++ b/README_th.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## ประวัติดาว -🎉 **40,000 ดาวบน GitHub — ขอบคุณทุกคน!** +🎉 **50,000 ดาวบน GitHub — ขอบคุณทุกคน!** ขอบคุณทุกคนที่ใช้ REA รายงานบั๊ก เสนอฟีเจอร์ ทดสอบบิลด์ และช่วยแก้ไข diff --git a/README_tr.md b/README_tr.md index ff5ae3239..6bf9ffd0d 100644 --- a/README_tr.md +++ b/README_tr.md @@ -256,7 +256,7 @@ Güvenlik açıklarını [SECURITY.md](SECURITY.md) üzerinden bildirin. ## Yıldız geçmişi -🎉 **GitHub'da 40.000 yıldız — teşekkürler!** +🎉 **GitHub'da 50.000 yıldız — teşekkürler!** REA'yı kullanan, hata bildiren, özellik talep eden, derlemeleri test eden ve düzeltmelere katkıda bulunan herkese teşekkürler. diff --git a/README_uk.md b/README_uk.md index 973ff9b41..c59b27bec 100644 --- a/README_uk.md +++ b/README_uk.md @@ -256,7 +256,7 @@ npx rea-agents@latest setup ## Історія зірок -🎉 **40 000 зірок на GitHub — дякуємо!** +🎉 **50 000 зірок на GitHub — дякуємо!** Дякуємо всім, хто використовує REA, повідомляє про помилки, пропонує нові функції, тестує збірки й допомагає з виправленнями. diff --git a/README_vi.md b/README_vi.md index 6f198f90f..cb33dd266 100644 --- a/README_vi.md +++ b/README_vi.md @@ -256,7 +256,7 @@ Báo cáo lỗ hổng theo [SECURITY.md](SECURITY.md). ## Lịch sử sao -🎉 **40.000 sao trên GitHub — xin cảm ơn!** +🎉 **50.000 sao trên GitHub — xin cảm ơn!** Cảm ơn mọi người đã sử dụng REA, báo lỗi, đề xuất tính năng, kiểm thử bản dựng và đóng góp bản sửa lỗi. diff --git a/README_zh-TW.md b/README_zh-TW.md index adef7444c..ec44d4c3e 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## Star 歷史 -🎉 **GitHub Star 達到 40,000 個,感謝大家!** +🎉 **GitHub Star 達到 50,000 個,感謝大家!** 感謝每一位使用 REA、報告錯誤、提出功能需求、測試建置和貢獻修復的朋友。 diff --git a/README_zh.md b/README_zh.md index baf67a145..6dca111fb 100644 --- a/README_zh.md +++ b/README_zh.md @@ -258,7 +258,7 @@ npx rea-agents@latest setup ## Star 历史 -🎉 **GitHub Star 达到 40,000 个,感谢大家!** +🎉 **GitHub Star 达到 50,000 个,感谢大家!** 感谢每一位使用 REA、报告错误、提出功能需求、测试构建和贡献修复的朋友。 From 98022a835275375ee0ffa88b7c8983ba6f080040 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:02:24 +0800 Subject: [PATCH 144/189] fix(javascript)!: avoid endpoint payload copies in graph metadata (#1423) Keep exact endpoint observations and request properties while using compact display labels and collision-safe canonical value digests for long artifact-local endpoint keys. Verify real CLI/stdio MCP tracing and version comparison without truncating evidence. BREAKING CHANGE: New analyses use compact endpoint labels and digest-based IDs for long or reserved-prefix endpoint keys. Select IDs from the parent graph and read full values from endpoint properties. Previously stored graphs retain their original identities and remain valid workflow inputs. --- docs/javascript-application-workflows.md | 14 + .../JavaScriptArtifactGraphFindings.ts | 19 +- .../JavaScriptSemanticGraphDataProjection.ts | 6 +- .../javascriptEndpointPayload.test.ts | 263 ++++++++++++++++++ 4 files changed, 295 insertions(+), 7 deletions(-) create mode 100644 tests/acceptance/applications/javascriptEndpointPayload.test.ts diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index 009371035..592276e15 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -104,6 +104,20 @@ graph and read literal values from `properties.value`, rather than decoding role keys or labels. Previously stored graphs and their original IDs remain valid inputs. +Endpoint nodes keep the exact endpoint in each observation's `properties.value`; +semantic request and response nodes keep it in `properties.endpoint`. Endpoint +identity keys use `value-sha256:` over the canonical JSON string when +that is shorter, or when the original value starts with the reserved digest +prefix. Other short endpoint keys remain unchanged. Endpoint labels use the +shorter of the exact value and ` endpoint`; semantic request/response +labels use the shorter of the endpoint and operation method. These labels are +display metadata, not endpoint lookup values. + +New analyses therefore change hashed endpoint IDs and longer endpoint labels. +Use IDs from the selected graph and read the complete endpoint properties; +previously stored graphs still support their original IDs. Literal endpoint +search, semantic tracing, and version comparison use the preserved values. + ## Version comparison REA pairs entities only when a tier produces one unique candidate on each side. diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts index cff140220..580a4d035 100644 --- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts +++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; +import { digestCanonicalValue } from "../../domain/canonicalDigest.js"; import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js"; import type { JavaScriptStaticAnalysis } from "../../domain/javascript/javascriptStaticAnalysisTypes.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; @@ -162,16 +163,22 @@ const addEndpoint = ( const source = sourceNodeFor(context, input.file.path, input.value.module_key) ?? input.asset; + const digestPrefix = "value-sha256:"; + const valueKey = `${digestPrefix}${digestCanonicalValue(input.value.value, "JavaScript endpoint")}`; + // Reserve the digest prefix so an exact caller value cannot alias a digest key. + const key = + input.value.value.length <= valueKey.length && + !input.value.value.startsWith(digestPrefix) + ? input.value.value + : valueKey; + const label = `${input.value.kind} endpoint`; const node = context.accumulator.addNode({ kind: "endpoint", - identity: artifactLocalIdentity( - input.file.sha256, - input.value.kind, - input.value.value, - ), + identity: artifactLocalIdentity(input.file.sha256, input.value.kind, key), observations: [ { - label: input.value.value, + label: + input.value.value.length <= label.length ? input.value.value : label, properties: { endpoint_kind: input.value.kind, value: input.value.value, diff --git a/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts b/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts index 51efcd2ec..b1c44e8f8 100644 --- a/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphDataProjection.ts @@ -137,7 +137,11 @@ const addRequestNode = ( kind: operation.kind === "request" ? "request" : "response", roleKey: operation.requestId, location: operation.location, - label: operation.endpoint ?? operation.method, + label: + operation.endpoint !== null && + operation.endpoint.length <= operation.method.length + ? operation.endpoint + : operation.method, functionNodeId: operation.ownerCallableId === null ? null diff --git a/tests/acceptance/applications/javascriptEndpointPayload.test.ts b/tests/acceptance/applications/javascriptEndpointPayload.test.ts new file mode 100644 index 000000000..6a980aa7a --- /dev/null +++ b/tests/acceptance/applications/javascriptEndpointPayload.test.ts @@ -0,0 +1,263 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { createHash } from "node:crypto"; +import { 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 { applicationVersionComparisonResultSchema } from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js"; +import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js"; +import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +cliTest( + "keeps full endpoint evidence usable without copying large values into metadata", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-endpoint-payload-"); + const endpoint = `https://example.invalid/${"part/ğ".repeat(160_000)}`; + const digestLookalike = `value-sha256:${createHash("sha256").update(JSON.stringify(endpoint)).digest("hex")}`; + // UTF-8 replacement would conflate these distinct JavaScript strings. + const surrogate = "\ud800".repeat(100); + const replacement = "\ufffd".repeat(100); + const values = [ + endpoint, + digestLookalike, + "/ok", + "/ok", + surrogate, + replacement, + ]; + const source = values + .map((value) => `fetch(${JSON.stringify(value)});`) + .join("\n"); + const sourcePath = join(root, "main.js"); + await writeFile(sourcePath, source); + const cliResponse = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + timeoutMs: 60_000, + }); + expect(cliResponse.exitCode).toBe(0); + const cliEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(cliResponse.json); + + const client = new Client({ name: "endpoint-payload-e2e", 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 response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + expect(response.isError).not.toBe(true); + const evidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(response.structuredContent); + expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); + const text = response.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + const textEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(JSON.parse(text.text)); + expect(textEvidence.evidence_id).toBe(evidence.evidence_id); + const result = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ); + const endpoints = result.graph.nodes.filter( + (node) => node.kind === "endpoint", + ); + const nodeFor = (value: string) => { + const node = endpoints.find((candidate) => + candidate.observations.some( + ({ properties }) => properties.value === value, + ), + ); + if (node === undefined) throw new Error("Complete endpoint was lost"); + return node; + }; + const endpointNode = nodeFor(endpoint); + expect( + new Set( + [endpoint, digestLookalike, surrogate, replacement].map( + (value) => nodeFor(value).node_id, + ), + ).size, + ).toBe(4); + const repeatedNode = nodeFor("/ok"); + expect( + endpoints.filter((node) => + node.observations.some( + ({ properties }) => properties.value === "/ok", + ), + ), + ).toHaveLength(1); + expect(repeatedNode.observations).toHaveLength(2); + expect(repeatedNode.identity).toMatchObject({ key: "/ok" }); + expect( + repeatedNode.observations.every(({ label }) => label === "/ok"), + ).toBe(true); + expect(endpointNode.identity).toMatchObject({ + artifact_sha256: createHash("sha256").update(source).digest("hex"), + }); + expect(endpointNode.observations[0]?.evidence.location).toMatchObject({ + available: true, + value: { kind: "source-range", source: "main.js" }, + }); + const requests = result.semantic_graph.nodes.filter( + (node) => + node.kind === "request" && node.properties.endpoint === endpoint, + ); + expect(requests).toHaveLength(1); + + await verifyEndpointWorkflows({ + client, + evidenceId: evidence.evidence_id, + endpoint, + endpointNodeId: endpointNode.node_id, + requestNodeIds: requests.map(({ node_id }) => node_id), + root, + source, + sourcePath, + }); + await client.ping(); + } finally { + await client.close(); + await transport.close(); + } + }, + 120_000, +); + +interface EndpointWorkflowInput { + readonly client: Client; + readonly evidenceId: string; + readonly endpoint: string; + readonly endpointNodeId: string; + readonly requestNodeIds: readonly string[]; + readonly root: string; + readonly source: string; + readonly sourcePath: string; +} + +const verifyEndpointWorkflows = async ({ + client, + evidenceId, + endpoint, + endpointNodeId, + requestNodeIds, + root, + source, + sourcePath, +}: EndpointWorkflowInput): Promise => { + const application = { + kind: "retained-evidence", + evidence_id: evidenceId, + }; + const featureResponse = await client.callTool({ + name: "trace_application_feature", + arguments: { + application, + seed: { + kind: "string", + value: endpoint, + match: "exact", + case_sensitive: true, + }, + }, + }); + expect(featureResponse.isError).not.toBe(true); + const featureEvidence = toolContract( + "trace_application_feature", + ).outputSchema.parse(featureResponse.structuredContent); + const feature = applicationFeatureTraceResultSchema.parse( + featureEvidence.normalized_result, + ); + expect(feature.seed_matches.map(({ node_id }) => node_id)).toContain( + endpointNodeId, + ); + + const traceResponse = await client.callTool({ + name: "trace_javascript_semantics", + arguments: { + application, + query: { + seed: { kind: "endpoint", value: endpoint }, + direction: "backward-provenance", + }, + }, + }); + expect(traceResponse.isError).not.toBe(true); + const traceEvidence = toolContract( + "trace_javascript_semantics", + ).outputSchema.parse(traceResponse.structuredContent); + const trace = javaScriptSemanticTraceResultSchema.parse( + traceEvidence.normalized_result, + ); + expect(trace.seed_node_ids).toEqual(requestNodeIds); + expect( + trace.nodes.some((node) => node.properties.endpoint === endpoint), + ).toBe(true); + + await writeFile(sourcePath, `// next artifact version\n${source}`); + const nextResponse = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + expect(nextResponse.isError).not.toBe(true); + const nextEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(nextResponse.structuredContent); + const next = javascriptApplicationAnalysisResultSchema.parse( + nextEvidence.normalized_result, + ); + const nextEndpoint = next.graph.nodes.find( + (node) => + node.kind === "endpoint" && + node.observations.some(({ properties }) => properties.value === endpoint), + ); + if (nextEndpoint === undefined) throw new Error("Next endpoint was lost"); + const comparisonResponse = await client.callTool({ + name: "compare_application_versions", + arguments: { + left: application, + right: { + kind: "retained-evidence", + evidence_id: nextEvidence.evidence_id, + }, + }, + }); + expect(comparisonResponse.isError).not.toBe(true); + const comparisonEvidence = toolContract( + "compare_application_versions", + ).outputSchema.parse(comparisonResponse.structuredContent); + const comparison = applicationVersionComparisonResultSchema.parse( + comparisonEvidence.normalized_result, + ); + expect(comparison.items).toContainEqual( + expect.objectContaining({ + node_kind: "endpoint", + left_node_id: endpointNodeId, + right_node_id: nextEndpoint.node_id, + match: expect.objectContaining({ + status: "matched", + basis: "semantic-key", + }), + }), + ); +}; From 28595276faac6a01dd4930313a91fab717d29513 Mon Sep 17 00:00:00 2001 From: Marnix Pluim Date: Sat, 10 Oct 2026 06:03:13 +0200 Subject: [PATCH 145/189] fix(javascript): bound member-mutation paths through reassignment loops Fixes #1401. Refs #1065. Preserve exact member facts and equal-depth write effects while bounding the observed reassignment-loop expansion. Validated with the JavaScript semantic/application suite, focused alias regressions, full static checks, real compiled CLI and SDK MCP Notion workflows, and all 20 checks on the final PR head. Co-Authored-By: Marnix Pluim <286664873+marnixpluim@users.noreply.github.com> Co-Authored-By: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Co-Authored-By: Claude --- ...manticAnalysis.reference_lifetimes.test.ts | 157 ++++++++++ .../javascriptSemanticMemberMutations.ts | 270 +++++++++++++++++- .../javascriptSemanticPropertyPaths.ts | 86 ++++++ .../javascript/javascriptSemanticValues.ts | 25 +- 4 files changed, 524 insertions(+), 14 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts index 2795427bd..73c7897b0 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.reference_lifetimes.test.ts @@ -9,6 +9,163 @@ const resultValue = (body: string) => "result", ).returnSites[0]?.value; +describe("bounded member path propagation", () => { + it("bounds cyclic member paths with no observed container origin", () => { + const branches = Array.from( + { length: 16 }, + (_, index) => `if (flag === ${index}) node = node.m${index};`, + ).join(" else "); + const start = performance.now(); + const callable = onlyCallable( + analyzeJavaScriptSemantics( + `export function result(seed) { let node=seed; while(node) { ${branches} use(node.state); } return seed.keep; }`, + ), + "result", + ); + expect(callable.returnSites[0]?.value.status).toBe("unknown"); + expect(performance.now() - start).toBeLessThan(2000); + }, 30000); + + it("preserves Array prototype effects through an otherwise unknown alias", () => { + expect( + resultValue( + "const values=[1]; const prototype=Array.prototype; prototype[Symbol.iterator]=custom; for(const item of values) { mutate(item); } return values[0];", + )?.status, + ).toBe("unknown"); + }); + + it("bounds loops derived from a scalar member while preserving sibling facts", () => { + const branches = Array.from( + { length: 16 }, + (_, index) => `if (flag === ${index}) node = node.m${index};`, + ).join(" else "); + const start = performance.now(); + expect( + resultValue( + `const source={child:1,keep:{value:3}}; let node=source.child; while(node) { ${branches} use(node.state); } return source.keep.value;`, + ), + ).toEqual({ status: "literal", value: 3 }); + expect(performance.now() - start).toBeLessThan(2000); + }, 30000); + + it.each([ + ["child:external,", "child", "present"], + ["", "missing", "unknown-coverage"], + ])( + "retains slot presence below an unobserved container: %s", + (property, name, presence) => { + expect( + resultValue( + `const source={${property}keep:3}; const alias=source.${name}; alias.deep.value=2; return source;`, + ), + ).toMatchObject({ + status: "object", + properties: expect.arrayContaining([ + { + name, + presence, + value: { + status: "unknown", + reason: "This property may have been mutated.", + }, + }, + { + name: "keep", + presence: "present", + value: { status: "literal", value: 3 }, + }, + ]), + }); + }, + ); + + it.each([ + ["use(node);", "m0.value", "unknown"], + ["node.value = 2;", "m0.value", "unknown"], + ["node.value = 2;", "mode", "literal"], + ])( + "bounds a loop that reassigns one reference through many members: %s seed.%s", + (effect, read, status) => { + const branches = Array.from( + { length: 9 }, + (_, index) => `if (flag === ${index}) node = node.m${index};`, + ).join(" else "); + const start = performance.now(); + const value = resultValue( + `const seed = { mode: "initial", m0: { value: 1 } }; let node = seed; while (node) { ${branches} ${effect} } return seed.${read};`, + ); + expect(performance.now() - start).toBeLessThan(2000); + expect(value?.status).toBe(status); + }, + 30000, + ); + + it.each([ + ["const alias = flag ? owner.child : owner; alias.value = 2;", "value"], + ["const alias = flag ? owner : owner.child; alias.value = 2;", "value"], + ["const alias = flag ? owner.child : owner; alias[key] = 2;", "value"], + [ + "const alias = flag ? owner.child : owner; alias.child = 2;", + "child.value", + ], + [ + "let alias = owner; let i = 0; while (i++ < 1) { alias = flag ? alias.child : alias; alias.value = 2; }", + "value", + ], + ])( + "keeps a write that reaches a child through a longer path: %s", + (body, read) => { + expect( + resultValue( + `const shared = { value: 1, child: { value: 1 } }; const owner = { child: shared }; ${body} return shared.${read};`, + )?.status, + ).toBe("unknown"); + }, + ); + + it.each([ + "mutate(source.left, source.right);", + "const alias = flag ? source.left : source.right; mutate(alias);", + "const copy = flag ? [source.left] : [source.right]; mutate(copy);", + "const alias = flag ? source.left : source.right; alias.value = 2;", + ])("keeps members outside the mutated paths: %s", (body) => { + expect( + resultValue( + `const source = { left: { value: 1 }, right: { value: 2 }, keep: { value: 3 } }; ${body} return source.keep.value;`, + ), + ).toEqual({ status: "literal", value: 3 }); + }); +}); + +describe("distinct observable mutation paths", () => { + it.each([ + ["alias.value = 2;", "left"], + ["alias.value = 2;", "right"], + ["mutate(alias);", "left"], + ["mutate(alias);", "right"], + ])( + "propagates both conditional paths to shared bindings: %s %s", + (effect, target) => { + expect( + resultValue( + `const left={value:1}; const right={value:2}; const source={left,right}; const alias=flag?source.left:source.right; ${effect} return ${target}.value;`, + )?.status, + ).toBe("unknown"); + }, + ); + + it.each(["mutate(alias);", "alias.value = 2;"])( + "preserves sibling facts below a shared prefix: %s", + (effect) => { + expect( + resultValue( + `const shared={left:{value:1},right:{value:2},keep:{value:3}}; const source={nested:shared}; const alias=flag?source.nested.left:source.nested.right; ${effect} return shared.keep.value;`, + ), + ).toEqual({ status: "literal", value: 3 }); + }, + ); +}); + describe("reference lifetimes across calls and shallow copies", () => { it("bounds dynamic destructuring across shared alias branches", () => { const declarations = Array.from( diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index ae887b9c7..21a6aded0 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -18,6 +18,7 @@ import { semanticIterationSources } from "./javascriptSemanticIterationSources.j import { semanticMutationInitializers } from "./javascriptSemanticMutationInitializers.js"; import { semanticArrayIndex, + SemanticPropertyPathCoverage, semanticPropertyPathKeyMatches, type JavaScriptSemanticPropertyPath, } from "./javascriptSemanticPropertyPaths.js"; @@ -42,8 +43,10 @@ export const collectSemanticMemberMutations = ( if (parent !== null) parents.set(node, parent); }, }); + const normalizePath = observableMutationPaths(state); const recordedEffects = new Set(); const selections = new Map(); + const coveringPaths = new Map(); let arrayIterationUnknown = false; const pendingReferences: { readonly initializer: JavaScriptSemanticBindingState["referenceInitializers"][number]; @@ -93,8 +96,10 @@ export const collectSemanticMemberMutations = ( originAt: t.Node | undefined = mutation, ): void => { const pending = [{ node, path, bindings, originAt }]; - while (pending.length > 0) { - const current = pending.pop(); + // Visit shallower alias traversals first so their exact prefixes suppress + // longer loop paths before those paths enumerate every assignment order. + for (let cursor = 0; cursor < pending.length; cursor++) { + const current = pending[cursor]; if (current === undefined) break; const expression = unwrapJavaScriptExpression(current.node).node; if (t.isIdentifier(expression)) { @@ -126,10 +131,13 @@ export const collectSemanticMemberMutations = ( if (current.bindings.has(lifetime)) continue; // Union compatible copied-slot selections at each binding. Carrying every // combination of exclusions through branch diamonds is exponential. - const selectorIndex = current.path.findIndex( + // Preserve paths that can change observed slots or Array prototype + // effects; canonicalize suffixes that cannot distinguish lattice facts. + let path = normalizePath(binding.bindingId, current.path, effect); + if (path === null) continue; + const selectorIndex = path.findIndex( (key) => key !== null && typeof key === "object", ); - let path = current.path; const selector = path[selectorIndex]; if (selector !== null && typeof selector === "object") { const selectionIdentity = JSON.stringify([ @@ -157,6 +165,25 @@ export const collectSemanticMemberMutations = ( index === selectorIndex ? { ...selector, excludedKeys } : key, ); } + // Keep an antichain of exact paths. Widening distinct member keys would + // also invalidate unrelated siblings that never reach this effect. + const pathState = JSON.stringify([ + binding.bindingId, + effect, + // Short writes stop at owned literal slots, whereas longer writes + // reach shared children. Only equal-depth writes cover one another. + effect === "write" ? path.length : null, + mutation?.start, + mutation?.end, + current.originAt?.start, + current.originAt?.end, + ]); + let covering = coveringPaths.get(pathState); + if (covering === undefined) { + covering = new SemanticPropertyPathCoverage(); + coveringPaths.set(pathState, covering); + } + if (!covering.retain(path)) continue; const identity = JSON.stringify([ binding.bindingId, effect, @@ -544,6 +571,241 @@ const referencedValues = ( return []; }; +type MutationObservableOrigin = + | t.ObjectExpression + | t.ArrayExpression + | "ambient" + | "array" + | "array-prototype" + | "opaque"; + +interface MutationObserverNode { + readonly origins: Set; + readonly sources: Set; + readonly dependents: Set; + readonly projections: Map; + readonly read?: { + readonly source: MutationObserverNode; + readonly key: PropertyPath[number]; + }; +} + +const observableMutationPaths = ( + state: JavaScriptSemanticAnalysisState, +): (( + bindingId: string, + path: PropertyPath, + effect: ValueEffect, +) => PropertyPath | null) => { + const bindingNodes = new Map(); + const expressions = new WeakMap(); + const pendingExpressions: { + readonly expression: t.Node; + readonly observer: MutationObserverNode; + }[] = []; + const pending: MutationObserverNode[] = []; + const queued = new Set(); + const schedule = (node: MutationObserverNode): void => { + if (queued.has(node)) return; + queued.add(node); + pending.push(node); + }; + const create = ( + read?: MutationObserverNode["read"], + ): MutationObserverNode => ({ + origins: new Set(), + sources: new Set(), + dependents: new Set(), + projections: new Map(), + ...(read === undefined ? {} : { read }), + }); + const link = ( + source: MutationObserverNode, + target: MutationObserverNode, + ): void => { + if (target.sources.has(source)) return; + target.sources.add(source); + source.dependents.add(target); + schedule(target); + }; + const expressionNode = (node: t.Node): MutationObserverNode => { + const expression = unwrapJavaScriptExpression(node).node; + const existing = expressions.get(expression); + if (existing !== undefined) return existing; + const observer = create(); + expressions.set(expression, observer); + pendingExpressions.push({ expression, observer }); + return observer; + }; + const project = ( + source: MutationObserverNode, + path: PropertyPath, + ): MutationObserverNode => { + let observer = source; + for (const key of path) { + const identity = JSON.stringify( + key === null || typeof key === "object" ? key : String(key), + ); + let selected = observer.projections.get(identity); + if (selected === undefined) { + selected = create({ source: observer, key }); + observer.projections.set(identity, selected); + observer.dependents.add(selected); + schedule(selected); + } + observer = selected; + } + return observer; + }; + for (const binding of state.bindingsById.values()) + bindingNodes.set(binding.bindingId, create()); + for (const binding of state.bindingsById.values()) { + const observer = bindingNodes.get(binding.bindingId); + if (observer === undefined) continue; + for (const initializer of binding.initializers) + link( + project(expressionNode(initializer.node), initializer.projection), + observer, + ); + // Preserve exact paths where copies, defaults or iteration need their + // reference-specific projections; an opaque origin prevents pruning. + if (binding.referenceInitializers.length > 0) + observer.origins.add("opaque"); + for (const initializer of binding.referenceInitializers) { + for (const source of [ + initializer, + ...(initializer.requiredSources ?? []), + ...(initializer.fallbackSources ?? []), + ]) + link(expressionNode(source.node), observer); + } + } + const settle = (): void => { + while (pendingExpressions.length > 0 || pending.length > 0) { + while (pendingExpressions.length > 0) { + const selected = pendingExpressions.pop(); + if (selected === undefined) break; + const { expression, observer } = selected; + if (t.isObjectExpression(expression) || t.isArrayExpression(expression)) + observer.origins.add(expression); + else if (t.isIdentifier(expression)) { + const binding = resolveSemanticBindingState( + state, + expression, + expression.name, + ); + if (binding !== undefined) { + const origin = bindingNodes.get(binding.bindingId); + if (origin !== undefined) link(origin, observer); + } else if (expression.name === "Array") observer.origins.add("array"); + else if ( + ["globalThis", "global", "window", "self"].includes(expression.name) + ) + observer.origins.add("ambient"); + } else if ( + t.isMemberExpression(expression) || + t.isOptionalMemberExpression(expression) + ) + link( + project(expressionNode(expression.object), [ + semanticStaticPropertyKey( + expression.property, + expression.computed, + ), + ]), + observer, + ); + else + for (const reference of referencedValues(expression, [], "escape")) + link( + project(expressionNode(reference.node), reference.path), + observer, + ); + schedule(observer); + } + const observer = pending.pop(); + if (observer === undefined) continue; + queued.delete(observer); + let changed = false; + const add = (origin: MutationObservableOrigin): void => { + if (observer.origins.has(origin)) return; + observer.origins.add(origin); + changed = true; + }; + for (const source of observer.sources) + for (const origin of source.origins) add(origin); + if (observer.read !== undefined) { + const { source, key } = observer.read; + if (key === null || typeof key === "object") { + // Dynamic keys and copied-slot masks retain their original paths. + // Enumerating their exclusion combinations would recreate the growth + // that the mutation collector's selection union already prevents. + if (source.origins.size > 0) add("opaque"); + } else + for (const origin of source.origins) { + if (typeof origin === "string") { + if (origin === "array-prototype" || origin === "opaque") + add(origin); + else if ( + origin === "ambient" && + semanticPropertyPathKeyMatches(key, "Array") + ) + add("array"); + else if ( + origin === "array" && + semanticPropertyPathKeyMatches(key, "prototype") + ) + add("array-prototype"); + } else { + for (const reference of referencedValues( + origin, + [key], + "escape", + )) { + link( + project(expressionNode(reference.node), reference.path), + observer, + ); + if (reference.iterableFallbackPath !== undefined) + link( + project( + expressionNode(reference.node), + reference.iterableFallbackPath, + ), + observer, + ); + } + } + } + } + if (changed) + for (const dependent of observer.dependents) schedule(dependent); + } + }; + settle(); + return (bindingId, path, effect) => { + let observer = bindingNodes.get(bindingId); + if (observer === undefined) return path; + if (path.some((key) => key !== null && typeof key === "object")) + return path; + if (effect === "escape") { + observer = project(observer, path); + settle(); + return observer.origins.size === 0 ? null : path; + } + if (observer.origins.size === 0) return path.length === 0 ? path : [null]; + for (let offset = 0; offset < path.length; offset++) { + const key = path[offset]; + if (key === undefined) break; + observer = project(observer, [key]); + settle(); + if (observer.origins.size === 0 && offset + 1 < path.length) + return [...path.slice(0, offset + 1), null]; + } + return path; + }; +}; + const objectReferencedValues = ( node: t.ObjectExpression, path: PropertyPath, diff --git a/src/domain/javascript/javascriptSemanticPropertyPaths.ts b/src/domain/javascript/javascriptSemanticPropertyPaths.ts index 9bee0e9b7..95cbeef97 100644 --- a/src/domain/javascript/javascriptSemanticPropertyPaths.ts +++ b/src/domain/javascript/javascriptSemanticPropertyPaths.ts @@ -35,3 +35,89 @@ export const semanticPropertyPathKeyMatches = ( const index = semanticArrayIndex(name); return index !== null && index >= key.startIndex; }; + +interface PropertyPathCoverageNode { + terminal: boolean; + readonly exact: Map; + readonly selectors: Map< + string, + { + readonly key: JavaScriptSemanticPropertyPath[number]; + readonly node: PropertyPathCoverageNode; + } + >; +} + +const coverageNode = (): PropertyPathCoverageNode => ({ + terminal: false, + exact: new Map(), + selectors: new Map(), +}); + +/** Index exact effect prefixes without widening distinct member paths. */ +export class SemanticPropertyPathCoverage { + readonly #root = coverageNode(); + + /** Retain a path only when no previously retained prefix covers it. */ + retain(path: JavaScriptSemanticPropertyPath): boolean { + const pending = [{ node: this.#root, offset: 0 }]; + while (pending.length > 0) { + const current = pending.pop(); + if (current === undefined) break; + if (current.node.terminal) return false; + const key = path[current.offset]; + if (key === undefined) continue; + if (key !== null && typeof key !== "object") { + const exact = current.node.exact.get(String(key)); + if (exact !== undefined) + pending.push({ node: exact, offset: current.offset + 1 }); + } + for (const selected of current.node.selectors.values()) { + if (keyCovers(selected.key, key)) + pending.push({ node: selected.node, offset: current.offset + 1 }); + } + } + let node = this.#root; + for (const key of path) { + if (key !== null && typeof key !== "object") { + const name = String(key); + let child = node.exact.get(name); + if (child === undefined) { + child = coverageNode(); + node.exact.set(name, child); + } + node = child; + } else { + const identity = JSON.stringify(key); + let selected = node.selectors.get(identity); + if (selected === undefined) { + selected = { key, node: coverageNode() }; + node.selectors.set(identity, selected); + } + node = selected.node; + } + } + node.terminal = true; + node.exact.clear(); + node.selectors.clear(); + return true; + } +} + +const keyCovers = ( + covering: JavaScriptSemanticPropertyPath[number], + key: JavaScriptSemanticPropertyPath[number], +): boolean => { + if (covering === null) return true; + if (key === null) return false; + if (typeof key !== "object") + return typeof covering === "object" + ? semanticPropertyPathKeyMatches(covering, String(key)) + : String(covering) === String(key); + return ( + typeof covering === "object" && + covering.excludedKeys.every((name) => key.excludedKeys.includes(name)) && + (covering.startIndex === undefined || + (key.startIndex !== undefined && covering.startIndex <= key.startIndex)) + ); +}; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 2f5362670..884915948 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -211,12 +211,17 @@ const evaluateBinding = ( if (isPrimitive(captured)) value = captured; } } - const mutated = binding.mutatedPaths.reduce( - invalidateSemanticMutationPath, - value, - ); - const projected = binding.escapedPaths.reduce( - (value, escape) => + let projected = value; + for (const path of binding.mutatedPaths) { + projected = invalidateSemanticMutationPath(projected, path); + // Every subsequent write returns this same root unknown. Replaying those + // paths at every newly collected effect otherwise becomes quadratic. + if (projected.status === "unknown") break; + } + for (const escape of binding.escapedPaths) { + // Escapes only invalidate object references; other lattice values survive. + if (projected.status !== "object" && projected.status !== "array") break; + if ( context.capturePoint !== undefined && semanticEscapeFollowsCapture( binding, @@ -224,10 +229,10 @@ const evaluateBinding = ( escape.node, context.state.parentsByNode, ) - ? value - : invalidateSemanticEscapedPath(value, escape.path), - mutated, - ); + ) + continue; + projected = invalidateSemanticEscapedPath(projected, escape.path); + } // Point-local memoization also bounds failed speculative captures. Only a // primitive result is allowed back into ordinary value evaluation. if ( From 4d95f2b2e7a6fdc1ba9dfcbd90578f6bbc5e5e1e Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:15:11 +0800 Subject: [PATCH 146/189] fix(validation): retain unmatched union correction details Preserve actionable field paths and schema-declared variants for unknown or missing discriminators. Closes #1421. Refs #1065. --- src/domain/inputIssueProjection.ts | 19 ++++++++- tests/boundary/cli/analysisViewCli.test.ts | 45 ++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/src/domain/inputIssueProjection.ts b/src/domain/inputIssueProjection.ts index 25798721c..1d5db83b6 100644 --- a/src/domain/inputIssueProjection.ts +++ b/src/domain/inputIssueProjection.ts @@ -35,7 +35,23 @@ const projectIssue = ( typeof part === "string" || typeof part === "number" ? [part] : [], ); // Branch issue paths are relative to the union; branches often agree. - if (issue.code === "invalid_union") + if (issue.code === "invalid_union") { + // Unmatched discriminators and ambiguous unions have no branch issues. + // Keep their outer failure instead of flattening it into an empty list. + if (issue.errors.length === 0) { + const expected = + "options" in issue ? issue.options?.filter(isSafeExpected) : undefined; + return [ + { + path, + reason: + valueAtPath(input, path) === undefined + ? "missing_argument" + : "invalid_value", + ...(expected === undefined ? {} : { expected }), + }, + ]; + } return uniqueIssues( issue.errors.flatMap((branch) => branch.flatMap((branchIssue) => @@ -46,6 +62,7 @@ const projectIssue = ( ), ), ); + } if (issue.code === "invalid_key") return issue.issues.flatMap((keyIssue) => projectIssue( diff --git a/tests/boundary/cli/analysisViewCli.test.ts b/tests/boundary/cli/analysisViewCli.test.ts index e6e6fb51d..86e0d9b27 100644 --- a/tests/boundary/cli/analysisViewCli.test.ts +++ b/tests/boundary/cli/analysisViewCli.test.ts @@ -80,3 +80,48 @@ cliTest("rejects a request that omits source", async ({ cli }) => { details: { operation: "inspect-analysis-view" }, }); }); + +for (const [view, reason] of [ + [{ kind: "unknown-view" }, "invalid_value"], + [{}, "missing_argument"], +] as const) { + cliTest( + `reports correction details for ${reason} view kind`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-view-variant-"); + const input = join(root, "view.json"); + await writeFile( + input, + JSON.stringify({ + source: { + kind: "inline", + evidence: analysisViewLayoutEvidence(), + }, + view, + }), + ); + const result = await cli.run({ + arguments: ["inspect-analysis-view", input, "--json"], + environment: { + HOME: root, + XDG_CONFIG_HOME: root, + XDG_CACHE_HOME: root, + }, + }); + expect(result.exitCode).toBe(1); + expect(result.json).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + { + path: ["view", "kind"], + reason, + expected: expect.arrayContaining(["summary", "page"]), + }, + ], + }, + }); + expect(JSON.stringify(result.json)).not.toContain("unknown-view"); + }, + ); +} From a9ee2360fd11332b2cc50ef7130a89321b828d28 Mon Sep 17 00:00:00 2001 From: jhuang-tw <77732008+jhuang-tw@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:18:50 +0800 Subject: [PATCH 147/189] feat(native): inspect oversized retained function dossiers via bounded views Add caller-selected native dossier facets with preserved Evidence identity, provenance, unknowns and transport recovery. Refs #1247 and #1065. Co-authored-by: jhuang-tw <77732008+jhuang-tw@users.noreply.github.com> Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> --- docs/mcp-contracts.md | 7 +- .../references/native-and-artifacts.md | 8 + .../analysisView/AnalysisViewService.test.ts | 92 ++++++++ .../analysisView/AnalysisViewService.ts | 18 +- src/cli/analysisViewCommands.ts | 2 +- src/contracts/analysisViewToolContracts.ts | 19 +- src/domain/analysisView/analysisView.test.ts | 197 +++++++++++++++-- src/domain/analysisView/analysisView.ts | 63 +++++- src/domain/analysisView/binaryLayoutView.ts | 4 + .../analysisView/javascriptApplicationView.ts | 4 + src/domain/analysisView/nativeFunctionView.ts | 202 ++++++++++++++++++ tests/boundary/cli/analysisViewCli.test.ts | 44 ++++ tests/boundary/mcp/analysisViewMcp.test.ts | 131 +++++++++++- 13 files changed, 769 insertions(+), 22 deletions(-) create mode 100644 src/domain/analysisView/nativeFunctionView.ts diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 5eedd9c14..7bf2fb76c 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -237,7 +237,12 @@ Ordinary responses keep their existing complete result contract. ## Retained application Evidence inputs `inspect_analysis_view` projects a caller-selected view of already completed -`inspect_binary_layout` or `analyze_javascript_application` Evidence. Source is +`inspect_binary_layout`, `analyze_javascript_application`, or `analyze_function` +Evidence. Native views select procedure, pseudocode, assembly, callers/callees, +references, and high-pcode facets without starting a provider. Native offset +and limit default to 0 and 64; pseudocode uses UTF-16 code units and never +splits surrogate pairs, while other pages count rows. Unavailable facts and +provider limitations remain explicit. Source is an exact same-session retained reference or portable inline Evidence. Views are a summary, a layout mitigations or linkage facet, one section/symbol/module, or a stable page with a caller-selected positive `limit`. Module pages include diff --git a/skill-src/reverse-engineer-anything/references/native-and-artifacts.md b/skill-src/reverse-engineer-anything/references/native-and-artifacts.md index f47017171..65b68c6b2 100644 --- a/skill-src/reverse-engineer-anything/references/native-and-artifacts.md +++ b/skill-src/reverse-engineer-anything/references/native-and-artifacts.md @@ -34,6 +34,14 @@ cross-references. Addresses and recovered pseudocode are analysis observations, not original source. Provider unavailability and unsupported metadata remain unknown rather than false. +For a completed `analyze_function` dossier, use `inspect_analysis_view` with +`view: {kind: "native", facet: "value_flow_operations", offset: 0, limit: 32}` +and the exact retained Evidence ID to read selected facts without reanalysis. +Native facets also include procedure, pseudocode, assembly, callers/callees, +references, and value-flow summaries. Pseudocode offsets and limits count UTF-16 +code units; use the returned `next_offset` for continuation. Provider limitations +and unavailable facts remain explicit; the complete parent Evidence is retained. + To see which functions or Objective-C methods a Mach-O actually calls in one run, use `observe_native_calls` with explicit breakpoints and a bounded `duration_ms`/`max_events`. It launches a new process under LLDB, so the target diff --git a/src/application/analysisView/AnalysisViewService.test.ts b/src/application/analysisView/AnalysisViewService.test.ts index 29289efae..b361e162f 100644 --- a/src/application/analysisView/AnalysisViewService.test.ts +++ b/src/application/analysisView/AnalysisViewService.test.ts @@ -2,6 +2,8 @@ import { expect, it } from "vitest"; import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js"; import { createEvidence, parseEvidence } from "../../domain/evidence.js"; +import { functionDossierSchema } from "../../domain/hopperValues.js"; +import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js"; import { analysisViewJavaScriptAnalysisWithSource, analysisViewJavaScriptEvidence, @@ -9,6 +11,96 @@ import { } from "../../../tests/fixtures/analysisView.js"; import { inspectAnalysisView } from "./AnalysisViewService.js"; +it.each(["/fixtures/unknown.exe", ""])( + "preserves recorded empty native identity fields: path=%j", + (path) => { + const original = functionDossierSchema.parse(ghidraFunctionDossier()); + const parent = createEvidence( + { path, format: "pe", sha256: "c".repeat(64) }, + { id: "ghidra", name: "Ghidra", version: "12.1.4" }, + { + operation: "analyze_function", + parameters: {}, + result: { + ...original, + procedure: { + ...original.procedure, + address: "", + body: { available: false, reason: "Not recorded" }, + }, + }, + }, + ); + const result = inspectAnalysisView({ + source: { kind: "inline", evidence: parent }, + view: { + kind: "native", + facet: "procedure", + offset: 0, + limit: 64, + }, + }); + if (!result.ok) throw result.error; + expect(result.value.normalized_result).toMatchObject({ + procedure_address: "", + artifact: { path }, + item: { address: "" }, + }); + expect(result.value.locations).toEqual( + path.length > 0 ? [{ kind: "artifact-path", path }] : [], + ); + }, +); + +it("projects a small native view from an authenticated >10 MiB retained dossier", () => { + const original = functionDossierSchema.parse(ghidraFunctionDossier()); + const parent = createEvidence( + { path: "/fixtures/large.exe", format: "pe", sha256: "c".repeat(64) }, + { id: "ghidra", name: "Ghidra", version: "12.1.4" }, + { + operation: "analyze_function", + parameters: { address: "0x401000" }, + result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) }, + limitations: ["Synthetic fixture"], + }, + ); + const input = { + source: { + kind: "retained-evidence" as const, + evidence_id: parent.evidence_id, + }, + view: { + kind: "native" as const, + facet: "pseudocode" as const, + offset: 0, + limit: 128, + }, + }; + const view = inspectAnalysisView(input, (id) => + id === parent.evidence_id ? parent : undefined, + ); + if (!view.ok) throw view.error; + expect(view.value.evidence_links).toEqual([parent.evidence_id]); + expect(view.value.normalized_result).toMatchObject({ + kind: "native", + parent_operation: "analyze_function", + parent_evidence_id: parent.evidence_id, + procedure_address: "0x401000", + artifact: { path: "/fixtures/large.exe", sha256: "c".repeat(64) }, + coverage: { total: 11 * 1024 * 1024, examined: 128, next_offset: 128 }, + }); + expect(view.value.locations).toEqual([ + { kind: "artifact-path", path: "/fixtures/large.exe" }, + { kind: "address", address: "0x401000" }, + ]); + expect(JSON.stringify(view.value).length).toBeLessThan(12000); + expect(JSON.stringify(parent).length).toBeGreaterThan(10 * 1024 * 1024); + expect(inspectAnalysisView(input, () => undefined)).toMatchObject({ + ok: false, + error: { _tag: "EvidenceIntegrityError" }, + }); +}); + it("projects inline layout Evidence and retains a derived view record", () => { const parent = analysisViewLayoutEvidence(); const result = inspectAnalysisView({ diff --git a/src/application/analysisView/AnalysisViewService.ts b/src/application/analysisView/AnalysisViewService.ts index 0d10d5fa8..7af6fb24a 100644 --- a/src/application/analysisView/AnalysisViewService.ts +++ b/src/application/analysisView/AnalysisViewService.ts @@ -53,6 +53,13 @@ export const inspectAnalysisViewValidated = ( operation: parent.operation, normalizedResult: parent.normalized_result, limitations: parent.limitations, + artifact: + parent.subject === null + ? null + : { + path: parent.subject.local_path, + sha256: parent.subject.digest.sha256, + }, }, input.view, ); @@ -126,7 +133,16 @@ const createAnalysisViewEvidence = ( confidence: "derived", authority: parent.authority, limitations: result.limitations, - locations: [{ kind: "artifact-path", path: result.artifact.path }], + locations: [ + ...(result.artifact.path.length > 0 + ? [{ kind: "artifact-path" as const, path: result.artifact.path }] + : []), + ...(result.kind === "native" && + result.procedure_address !== null && + result.procedure_address.length > 0 + ? [{ kind: "address" as const, address: result.procedure_address }] + : []), + ], evidenceLinks: [parent.evidence_id], }); }; diff --git a/src/cli/analysisViewCommands.ts b/src/cli/analysisViewCommands.ts index a0deb0229..a193d2740 100644 --- a/src/cli/analysisViewCommands.ts +++ b/src/cli/analysisViewCommands.ts @@ -18,7 +18,7 @@ export const registerAnalysisViewCommands = ( ): void => { cli.command(CLI_COMMANDS.inspectAnalysisView, { description: - "Project a selected view of completed layout or JavaScript application Evidence JSON", + "Project a selected view of completed layout, JavaScript application or native function Evidence JSON", args: z.object({ inputJson: z.string().describe("Inline workflow JSON or JSON file path"), }), diff --git a/src/contracts/analysisViewToolContracts.ts b/src/contracts/analysisViewToolContracts.ts index b8f455767..be65b229f 100644 --- a/src/contracts/analysisViewToolContracts.ts +++ b/src/contracts/analysisViewToolContracts.ts @@ -8,14 +8,14 @@ import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js"; const RETAINED_EXAMPLE_ID = `ev_${"a".repeat(64)}`; -/** Selected views of already completed layout and JavaScript analysis Evidence. */ +/** Selected views of already completed layout, JavaScript and native function Evidence. */ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [ { name: "inspect_analysis_view", ...toolContractMetadata("inspect_analysis_view"), kind: "application", description: - "Inspect a selected view of completed binary-layout or JavaScript application Evidence without repeating analysis. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page with a positive limit. Module pages contain JavaScript assets, bundled modules and source modules; use node_id when paths are ambiguous or unavailable. Returns selected facts inline with artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the retained Evidence when needed.", + "Inspect selected views of completed binary-layout, JavaScript application or native analyze_function Evidence without repeating analysis. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Native views select procedure, pseudocode, assembly, callers/callees, references and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.", inputSchema: inspectAnalysisViewInputSchema, outputSchema: evidenceResultOf(analysisViewResultSchema), examples: [ @@ -43,6 +43,21 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [ }, }, }, + { + title: "Page native high-pcode operations from retained Evidence", + input: { + source: { + kind: "retained-evidence", + evidence_id: RETAINED_EXAMPLE_ID, + }, + view: { + kind: "native", + facet: "value_flow_operations", + offset: 0, + limit: 32, + }, + }, + }, { title: "Page module identities from retained application Evidence", input: { diff --git a/src/domain/analysisView/analysisView.test.ts b/src/domain/analysisView/analysisView.test.ts index e3aabcf14..1fd6fb7f1 100644 --- a/src/domain/analysisView/analysisView.test.ts +++ b/src/domain/analysisView/analysisView.test.ts @@ -1,6 +1,8 @@ import { expect, it } from "vitest"; import { resolveJavaScriptSourceMapReference } from "../javascript/javascriptSourceMapPaths.js"; +import { functionDossierSchema } from "../hopperValues.js"; +import { ghidraFunctionDossier } from "../ghidraValues.fixture.js"; import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js"; import { analysisViewBindJavaScriptGraphs, @@ -48,21 +50,190 @@ const javascriptParent = ( limitations: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE.limitations, }); -it("accepts caller-selected page sizes and rejects malformed bounds", () => { - const input = { - source: { kind: "retained-evidence", evidence_id: `ev_${"a".repeat(64)}` }, - view: { kind: "page", collection: "sections", offset: 0, limit: 500 }, - }; - expect(inspectAnalysisViewInputSchema.safeParse(input).success).toBe(true); - for (const limit of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) - expect( - inspectAnalysisViewInputSchema.safeParse({ - ...input, - view: { ...input.view, limit }, - }).success, - ).toBe(false); +const nativeParent = ( + result: unknown = ghidraFunctionDossier(), +): AnalysisViewParent => ({ + evidenceId: "ev_" + "b".repeat(64), + operation: "analyze_function", + normalizedResult: result, + limitations: ["Retained provider limitation"], + artifact: { path: "/fixtures/example.exe", sha256: "a".repeat(64) }, }); +it("projects native procedure and bounded assembly and high-pcode with exact parent identity", () => { + const parent = nativeParent(); + const procedure = projectAnalysisView(parent, { + kind: "native", + facet: "procedure", + offset: 0, + limit: 64, + }); + if (!procedure.ok) throw procedure.error; + expect(procedure.value).toMatchObject({ + kind: "native", + parent_operation: "analyze_function", + artifact: parent.artifact, + item: { address: "0x401000" }, + }); + expect(procedure.value.view_digest).not.toBe(parent.evidenceId.slice(3)); + const assembly = projectAnalysisView(parent, { + kind: "native", + facet: "assembly", + offset: 0, + limit: 1, + }); + if (!assembly.ok) throw assembly.error; + expect(assembly.value).toMatchObject({ + coverage: { examined: 1, total: 2, next_offset: 1 }, + item: ["0x401000: CALL 0x401020"], + }); + const flow = projectAnalysisView(parent, { + kind: "native", + facet: "value_flow_operations", + offset: 0, + limit: 1, + }); + if (!flow.ok) throw flow.error; + expect(flow.value).toMatchObject({ item: [{ opcode: "COPY" }] }); +}); + +it("rejects invalid native parents, unsupported source operations and singleton offsets", () => { + const view = { + kind: "native", + facet: "assembly", + offset: 0, + limit: 4, + } as const; + expect(projectAnalysisView(nativeParent({}), view)).toMatchObject({ + ok: false, + error: { _tag: "AnalysisInputError" }, + }); + expect( + projectAnalysisView({ ...nativeParent(), artifact: null }, view), + ).toMatchObject({ + ok: false, + error: { _tag: "AnalysisInputError" }, + }); + expect(projectAnalysisView(layoutParent(), view)).toMatchObject({ + ok: false, + error: { _tag: "AnalysisInputError" }, + }); + expect(projectAnalysisView(javascriptParent(), view)).toMatchObject({ + ok: false, + error: { _tag: "AnalysisInputError" }, + }); + expect( + projectAnalysisView(nativeParent(), { + kind: "native", + facet: "procedure", + offset: 1, + limit: 2, + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } }); +}); + +it("preserves native API limitations and unavailable residual unknowns", () => { + const original = functionDossierSchema.parse(ghidraFunctionDossier()); + const view = { + kind: "native", + facet: "procedure", + offset: 0, + limit: 64, + } as const; + const unavailable = projectAnalysisView( + nativeParent({ + ...original, + native_api: { + available: false, + reason: "No decompiler", + residual_unknowns: ["Calling convention unresolved"], + }, + }), + view, + ); + if (!unavailable.ok) throw unavailable.error; + expect(unavailable.value.unknowns).toContain("Calling convention unresolved"); + const available = projectAnalysisView(nativeParent(), view); + if (!available.ok) throw available.error; + if (!original.native_api?.available) throw new Error("expected API fixture"); + expect(available.value.limitations).toEqual( + expect.arrayContaining(original.native_api.limitations), + ); +}); + +it("reports the malformed native dossier field", () => { + const result = projectAnalysisView( + nativeParent({ + ...functionDossierSchema.parse(ghidraFunctionDossier()), + pseudocode: 12, + }), + { + kind: "native", + facet: "pseudocode", + offset: 0, + limit: 64, + }, + ); + expect(result).toMatchObject({ + ok: false, + error: { + issues: expect.arrayContaining([ + expect.objectContaining({ + path: ["source", "normalized_result", "pseudocode"], + }), + ]), + }, + }); +}); + +it("native pseudocode pages do not split surrogate pairs", () => { + const original = functionDossierSchema.parse(ghidraFunctionDossier()); + const parent = nativeParent({ ...original, pseudocode: "ab😀cd" }); + expect( + projectAnalysisView(parent, { + kind: "native", + facet: "pseudocode", + offset: 3, + limit: 2, + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } }); + const safe = projectAnalysisView(parent, { + kind: "native", + facet: "pseudocode", + offset: 2, + limit: 3, + }); + if (!safe.ok) throw safe.error; + expect(safe.value).toMatchObject({ + item: { text: "😀c", unit: "utf16-code-units" }, + coverage: { examined: 3, next_offset: 5 }, + }); +}); + +it.each([ + { kind: "page", collection: "sections", offset: 0, limit: 500 }, + { kind: "native", facet: "assembly", offset: 0, limit: 500 }, +])( + "accepts caller-selected page sizes and rejects malformed bounds: $kind", + (view) => { + const input = { + source: { + kind: "retained-evidence", + evidence_id: `ev_${"a".repeat(64)}`, + }, + view, + }; + expect(inspectAnalysisViewInputSchema.safeParse(input).success).toBe(true); + for (const limit of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) + expect( + inspectAnalysisViewInputSchema.safeParse({ + ...input, + view: { ...input.view, limit }, + }).success, + ).toBe(false); + }, +); + it("projects layout summary, facet, item, and stable pages", () => { const parent = layoutParent(); const layout = analysisViewLayoutFixture(); diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index efb9f5d44..db2d2dbac 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -12,6 +12,7 @@ import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js"; import { err, ok, type Result } from "../result.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { binaryLayoutSchema } from "../native/binaryLayout.js"; +import { functionDossierSchema } from "../hopperValues.js"; import { parseOwnedJavaScriptApplicationAnalysisSteps, type JavaScriptApplicationAnalysisResult, @@ -19,6 +20,7 @@ import { import { analysisInputErrorFromIssues } from "../inputIssueProjection.js"; import { projectBinaryLayoutView } from "./binaryLayoutView.js"; import { projectJavaScriptApplicationView } from "./javascriptApplicationView.js"; +import { projectNativeFunctionView } from "./nativeFunctionView.js"; /** Public name of the selected-view workflow. */ export const INSPECT_ANALYSIS_VIEW_OPERATION = "inspect_analysis_view" as const; @@ -73,12 +75,35 @@ const pageViewSchema = z.strictObject({ limit: z.number().int().positive(), }); +/** Bounded native function facets of already authenticated analyze_function Evidence. */ +const nativeViewSchema = z.strictObject({ + kind: z.literal("native"), + facet: z.enum([ + "procedure", + "pseudocode", + "assembly", + "callers", + "callees", + "incoming_references", + "outgoing_references", + "value_flow_summary", + "value_flow_operations", + "value_flow_def_use", + "value_flow_effects", + "value_flow_parameters", + "value_flow_parameter_uses", + ]), + offset: z.number().int().nonnegative().default(0), + limit: z.number().int().positive().default(64), +}); + /** Caller-selected projection of already completed analysis Evidence. */ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ summaryViewSchema, facetViewSchema, itemViewSchema, pageViewSchema, + nativeViewSchema, ]); /** Inline Evidence or an exact same-session retained reference. */ @@ -108,7 +133,9 @@ const coverageSchema = z.strictObject({ }); const artifactSchema = z.strictObject({ - path: z.string().min(1), + path: z + .string() + .describe("Exact recorded artifact path, including an empty string."), sha256: digestSchema, }); @@ -150,6 +177,7 @@ const viewResultBase = { parent_operation: z.enum([ "inspect_binary_layout", "analyze_javascript_application", + "analyze_function", ]), parent_digest: digestSchema, view_digest: digestSchema, @@ -185,6 +213,13 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ items: z.array(jsonValueSchema), ...viewResultBase, }), + z.strictObject({ + kind: z.literal("native"), + view: nativeViewSchema, + procedure_address: z.string().nullable(), + item: jsonValueSchema, + ...viewResultBase, + }), ]); export type AnalysisViewRequest = z.output; @@ -200,6 +235,7 @@ export interface AnalysisViewParent { readonly operation: string; readonly normalizedResult: unknown; readonly limitations: readonly string[]; + readonly artifact?: { readonly path: string; readonly sha256: string } | null; } /** Construct a typed input failure for one selected-view constraint. */ @@ -216,7 +252,11 @@ export type UnsignedAnalysisView = > | Omit, "view_digest"> | Omit, "view_digest"> - | Omit, "view_digest">; + | Omit, "view_digest"> + | Omit< + Extract, + "view_digest" + >; /** Attach the content digest that must change when projected bytes change. */ export const sealAnalysisView = ( @@ -261,7 +301,7 @@ const unsupportedParent = ( new AnalysisUnsupportedTargetError( INSPECT_ANALYSIS_VIEW_OPERATION, parentArtifactPath(parent), - `Parent Evidence operation ${JSON.stringify(parent.operation)} is not inspect_binary_layout or analyze_javascript_application.`, + `Parent Evidence operation ${JSON.stringify(parent.operation)} is not inspect_binary_layout, analyze_javascript_application or analyze_function.`, ); const parentArtifactPath = (parent: AnalysisViewParent): string => { @@ -327,5 +367,22 @@ export const projectAnalysisView = ( ); return projected.ok ? ok(sealAnalysisView(projected.value)) : projected; } + if (parent.operation === "analyze_function") { + const native = functionDossierSchema.safeParse(parent.normalizedResult); + if (!native.success) + return err( + analysisInputErrorFromIssues( + INSPECT_ANALYSIS_VIEW_OPERATION, + native.error.issues.map((issue) => ({ + ...issue, + path: ["source", "normalized_result", ...issue.path], + })), + { source: { normalized_result: parent.normalizedResult } }, + { cause: native.error }, + ), + ); + const projected = projectNativeFunctionView(parent, native.data, view); + return projected.ok ? ok(sealAnalysisView(projected.value)) : projected; + } return err(unsupportedParent(parent)); }; diff --git a/src/domain/analysisView/binaryLayoutView.ts b/src/domain/analysisView/binaryLayoutView.ts index 5a52904a8..13a9b766f 100644 --- a/src/domain/analysisView/binaryLayoutView.ts +++ b/src/domain/analysisView/binaryLayoutView.ts @@ -152,6 +152,10 @@ export const projectBinaryLayoutView = ( view: AnalysisViewRequest, ): Result => { const shared = parentFields(parent, layout); + if (view.kind === "native") + return err( + layoutIncompatible("Native views require analyze_function Evidence."), + ); if (view.kind === "summary") return ok({ kind: "summary", diff --git a/src/domain/analysisView/javascriptApplicationView.ts b/src/domain/analysisView/javascriptApplicationView.ts index 5216c72b4..d6e994fc9 100644 --- a/src/domain/analysisView/javascriptApplicationView.ts +++ b/src/domain/analysisView/javascriptApplicationView.ts @@ -243,6 +243,10 @@ export const projectJavaScriptApplicationView = ( ): Result => { const shared = parentFields(parent, analysis); const modules = moduleEntries(analysis.graph.nodes); + if (view.kind === "native") + return err( + jsIncompatible("Native views require analyze_function Evidence."), + ); if (view.kind === "summary") return ok({ kind: "summary", diff --git a/src/domain/analysisView/nativeFunctionView.ts b/src/domain/analysisView/nativeFunctionView.ts new file mode 100644 index 000000000..d17f69b03 --- /dev/null +++ b/src/domain/analysisView/nativeFunctionView.ts @@ -0,0 +1,202 @@ +import type { AnalysisError } from "../analysisErrorBase.js"; +import { uniqueSorted } from "../canonicalOrdering.js"; +import type { FunctionDossier } from "../hopperValues.js"; +import { jsonValueSchema } from "../jsonValue.js"; +import { err, ok, type Result } from "../result.js"; +import { + analysisViewInputError, + type AnalysisViewCoverage, + type AnalysisViewParent, + type AnalysisViewRequest, + type UnsignedAnalysisView, +} from "./analysisView.js"; +import { + completeWithinViewCoverage, + pageViewCoverage, +} from "./analysisViewCoverage.js"; + +type Artifact = { readonly path: string; readonly sha256: string }; + +const viewError = (message: string): AnalysisError => + analysisViewInputError([ + { path: ["view"], reason: "invalid_value", message }, + ]); + +const parentFields = ( + parent: AnalysisViewParent, + dossier: FunctionDossier, + artifact: Artifact, +) => { + const flow = dossier.native_value_flow; + const api = dossier.native_api; + const unknowns: string[] = []; + if (flow === null) unknowns.push("native_value_flow was not recorded"); + else if (!flow.available) + unknowns.push("native_value_flow unavailable: " + flow.reason); + else if (flow.truncated) + unknowns.push( + "native_value_flow is truncated; omitted observations remain unknown", + ); + if (api === null) unknowns.push("native_api was not recorded"); + else if (!api.available) + unknowns.push( + "native_api unavailable: " + api.reason, + ...api.residual_unknowns, + ); + return { + parent_evidence_id: parent.evidenceId, + parent_operation: "analyze_function" as const, + parent_digest: parent.evidenceId.slice(3), + procedure_address: dossier.procedure.address, + artifact, + limitations: uniqueSorted([ + ...parent.limitations, + ...dossier.limitations, + ...(flow?.limitations ?? []), + ...(api?.available ? api.limitations : []), + ]), + unknowns: uniqueSorted(unknowns), + }; +}; + +const pseudocodePage = ( + body: string, + offset: number, + limit: number, +): Result< + { + readonly item: { readonly text: string; readonly unit: "utf16-code-units" }; + readonly coverage: AnalysisViewCoverage; + }, + AnalysisError +> => { + const start = Math.min(offset, body.length); + const high = (n: number) => n >= 0xd800 && n <= 0xdbff; + const low = (n: number) => n >= 0xdc00 && n <= 0xdfff; + if ( + start > 0 && + start < body.length && + high(body.charCodeAt(start - 1)) && + low(body.charCodeAt(start)) + ) + return err(viewError("Pseudocode offset splits a UTF-16 surrogate pair.")); + let end = Math.min(start + limit, body.length); + if ( + end > start && + end < body.length && + high(body.charCodeAt(end - 1)) && + low(body.charCodeAt(end)) + ) + end--; + if (end === start && start < body.length) + return err( + viewError( + "Increase pseudocode limit to include the next complete Unicode character.", + ), + ); + return ok({ + item: { text: body.slice(start, end), unit: "utf16-code-units" }, + coverage: pageViewCoverage(start, end - start, body.length), + }); +}; + +const nativeRows = ( + dossier: FunctionDossier, + facet: Exclude< + Extract["facet"], + "procedure" | "pseudocode" | "value_flow_summary" + >, +) => { + const sourceFlow = dossier.native_value_flow; + const flow = sourceFlow?.available ? sourceFlow : undefined; + return { + assembly: dossier.assembly, + callers: dossier.callers, + callees: dossier.callees, + incoming_references: dossier.incoming_references, + outgoing_references: dossier.outgoing_references, + value_flow_operations: flow?.operations, + value_flow_def_use: flow?.def_use, + value_flow_effects: flow?.effects, + value_flow_parameters: flow?.parameters, + value_flow_parameter_uses: flow?.parameter_uses, + }[facet]; +}; + +/** Project bounded native function facets from complete retained Evidence without reanalysis. */ +export const projectNativeFunctionView = ( + parent: AnalysisViewParent, + dossier: FunctionDossier, + view: AnalysisViewRequest, +): Result => { + if (view.kind !== "native") + return err(viewError("analyze_function Evidence requires a native view.")); + const artifact = parent.artifact; + if (!artifact) + return err( + analysisViewInputError([ + { + path: ["source", "subject"], + reason: "invalid_value", + message: + "Native function Evidence requires an artifact-bound subject.", + }, + ]), + ); + const common = parentFields(parent, dossier, artifact); + const singleton = (item: unknown): UnsignedAnalysisView => ({ + kind: "native", + view, + item: jsonValueSchema.parse(item), + coverage: completeWithinViewCoverage(1, 1), + ...common, + }); + const flow = dossier.native_value_flow; + if (view.facet === "procedure" || view.facet === "value_flow_summary") { + if (view.offset !== 0) + return err(viewError("Singleton native facets require offset 0.")); + if (view.facet === "procedure") return ok(singleton(dossier.procedure)); + const status = + flow === null + ? { available: false, reason: "not recorded" } + : !flow.available + ? { available: false, reason: flow.reason } + : { + available: true, + provenance: flow.provenance, + truncated: flow.truncated, + omitted_operations_lower_bound: + flow.omitted_operations_lower_bound, + known_omitted_inputs: flow.known_omitted_inputs, + known_omitted_edges: flow.known_omitted_edges, + operations: flow.operations.length, + def_use: flow.def_use.length, + effects: flow.effects.length, + parameters: flow.parameters.length, + parameter_uses: flow.parameter_uses.length, + }; + return ok(singleton(status)); + } + if (view.facet === "pseudocode") { + const page = pseudocodePage(dossier.pseudocode, view.offset, view.limit); + return page.ok + ? ok({ kind: "native", view, ...page.value, ...common }) + : page; + } + const rows = nativeRows(dossier, view.facet); + if (rows === undefined) + return ok( + singleton({ + available: false, + reason: flow?.available === false ? flow.reason : "not recorded", + }), + ); + const items = rows.slice(view.offset, view.offset + view.limit); + return ok({ + kind: "native", + view, + item: jsonValueSchema.parse(items), + coverage: pageViewCoverage(view.offset, items.length, rows.length), + ...common, + }); +}; diff --git a/tests/boundary/cli/analysisViewCli.test.ts b/tests/boundary/cli/analysisViewCli.test.ts index 86e0d9b27..2abaf700a 100644 --- a/tests/boundary/cli/analysisViewCli.test.ts +++ b/tests/boundary/cli/analysisViewCli.test.ts @@ -7,6 +7,8 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js"; +import { createEvidence } from "../../../src/domain/evidence.js"; +import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js"; cliTest( "projects one section from a JSON file of inline layout Evidence", async ({ cli }) => { @@ -43,6 +45,48 @@ cliTest( }, ); +cliTest( + "projects native function pseudocode without requiring Ghidra", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-native-view-cli-"); + const parent = createEvidence( + { path: "/fixtures/native.exe", format: "pe", sha256: "a".repeat(64) }, + { id: "ghidra", name: "Ghidra", version: "12.1.4" }, + { + operation: "analyze_function", + parameters: { address: "0x401000" }, + result: ghidraFunctionDossier(), + }, + ); + const input = join(root, "native-view.json"); + await writeFile( + input, + JSON.stringify({ + source: { kind: "inline", evidence: parent }, + view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 }, + }), + ); + const result = await cli.run({ + arguments: ["inspect-analysis-view", input, "--json"], + environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root }, + }); + expect(result.exitCode).toBe(0); + expect(result.json).toMatchObject({ + operation: "inspect_analysis_view", + normalized_result: { + kind: "native", + parent_evidence_id: parent.evidence_id, + procedure_address: "0x401000", + item: { text: "int fixture_", unit: "utf16-code-units" }, + }, + locations: [ + { kind: "artifact-path", path: "/fixtures/native.exe" }, + { kind: "address", address: "0x401000" }, + ], + }); + }, +); + cliTest("rejects malformed JSON before projection", async ({ cli }) => { const root = await createTestTempDirectory("rea-analysis-view-cli-bad-"); const result = await cli.run({ diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index 3edeffba7..3c15312aa 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -6,7 +6,9 @@ import { z } from "zod"; import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; -import { parseEvidence } from "../../../src/domain/evidence.js"; +import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js"; +import { functionDossierSchema } from "../../../src/domain/hopperValues.js"; +import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js"; import { ok } from "../../../src/domain/result.js"; import { createJavaScriptApplicationGraph, @@ -109,6 +111,68 @@ it("advertises exact schemas and projects one layout section from retained Evide ); }); +it("delivers a bounded native dossier view over MCP without a Ghidra provider or lost connection", async () => { + const { client, session } = await connect(); + const original = functionDossierSchema.parse(ghidraFunctionDossier()); + const parent = createEvidence( + { + path: "/fixtures/oversized-native.exe", + format: "pe", + sha256: "b".repeat(64), + }, + { id: "ghidra", name: "Ghidra", version: "12.1.4" }, + { + operation: "analyze_function", + parameters: { address: "0x401000" }, + result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) }, + }, + ); + expect(session.recordEvidence(parent).ok).toBe(true); + const advertised = (await client.listTools()).tools.find( + (tool) => tool.name === "inspect_analysis_view", + ); + if (advertised?.outputSchema === undefined) + throw new Error("missing view schemas"); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + const inputSchema: Record = advertised.inputSchema; + const outputSchema: Record = advertised.outputSchema; + const arguments_ = { + source: { kind: "retained-evidence", evidence_id: parent.evidence_id }, + view: { kind: "native", facet: "pseudocode", offset: 0, limit: 500 }, + }; + expect(ajv.validateSchema(inputSchema)).toBe(true); + expect(ajv.validateSchema(outputSchema)).toBe(true); + expect( + ajv.validate(inputSchema, arguments_), + JSON.stringify(ajv.errors), + ).toBe(true); + const response = await client.callTool({ + name: "inspect_analysis_view", + arguments: arguments_, + }); + expect(response.isError).not.toBe(true); + expect( + ajv.validate(outputSchema, response.structuredContent), + JSON.stringify(ajv.errors), + ).toBe(true); + const parsed = toolContract("inspect_analysis_view").outputSchema.parse( + response.structuredContent, + ); + expect(parsed.normalized_result).toMatchObject({ + kind: "native", + parent_evidence_id: parent.evidence_id, + procedure_address: "0x401000", + coverage: { examined: 500, next_offset: 500, total: 11 * 1024 * 1024 }, + }); + expect(parsed.evidence_links).toEqual([parent.evidence_id]); + expect(parsed.locations).toEqual([ + { kind: "artifact-path", path: "/fixtures/oversized-native.exe" }, + { kind: "address", address: "0x401000" }, + ]); + expect(JSON.stringify(response.structuredContent).length).toBeLessThan(12000); + await client.ping(); +}); + it("retains an oversized selected observation and keeps subsequent views usable", async () => { const { client, session } = await connect(); const analysis = analysisViewJavaScriptAnalysisWithSource(); @@ -185,6 +249,71 @@ it("retains an oversized selected observation and keeps subsequent views usable" expect(summary.isError).not.toBe(true); }); +it("retains an oversized native assembly row and permits a subsequent smaller view", async () => { + const { client, session } = await connect(); + const row = "\0".repeat(1_000_000); + const parent = createEvidence( + { path: "/fixtures/large-row.exe", format: "pe", sha256: "c".repeat(64) }, + { id: "ghidra", name: "Ghidra", version: "12.1.4" }, + { + operation: "analyze_function", + parameters: {}, + result: { + ...functionDossierSchema.parse(ghidraFunctionDossier()), + assembly: [row], + }, + }, + ); + expect(session.recordEvidence(parent).ok).toBe(true); + const source = { kind: "retained-evidence", evidence_id: parent.evidence_id }; + const response = await client.callTool({ + name: "inspect_analysis_view", + arguments: { + source, + view: { kind: "native", facet: "assembly", offset: 0, limit: 1 }, + }, + }); + expect(response.isError).toBe(true); + const error = z + .object({ + error: z.object({ + details: z.object({ + reported_limits: z.object({ + evidence_reference: z.object({ + kind: z.literal("retained-evidence"), + evidence_id: z.string(), + }), + }), + }), + }), + }) + .parse(parseMcpToolError(response)); + const retained = session.evidenceById( + error.error.details.reported_limits.evidence_reference.evidence_id, + ); + expect(retained?.normalized_result).toMatchObject({ + item: [row], + parent_evidence_id: parent.evidence_id, + }); + const next = await client.callTool({ + name: "inspect_analysis_view", + arguments: { + source, + view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 }, + }, + }); + expect(next.isError).not.toBe(true); + expect( + toolContract("inspect_analysis_view").outputSchema.parse( + next.structuredContent, + ).normalized_result, + ).toMatchObject({ + item: { text: "int fixture_" }, + parent_evidence_id: parent.evidence_id, + }); + await client.ping(); +}); + it("returns a JavaScript summary without graph payloads from a retained reference", async () => { const { client, session } = await connect(); const parent = analysisViewJavaScriptEvidence(); From f4a0c1ce95375c1661ca95b414829113a10298b8 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:20:05 +0800 Subject: [PATCH 148/189] fix(javascript)!: avoid event payload copies in graph metadata (#1427) Share the canonical string identity rule with endpoint projection, scope event keys to each emitter, and keep complete event/listener names in properties. Verify real CLI and stdio MCP with large names, registration/removal, distinct emitters, exact name seeds, reserved-prefix values, and unresolved dynamic names. BREAKING CHANGE: New analyses use digest-based IDs for long or reserved-prefix event names and shorter event/listener display labels. Select IDs from the parent graph and read exact names from event_name properties. Stored graphs and their original IDs remain accepted for semantic tracing. --- docs/javascript-application-workflows.md | 10 ++ .../JavaScriptArtifactGraphFindings.ts | 11 +- .../JavaScriptSemanticGraphAsyncProjection.ts | 13 +- src/domain/compactStringIdentity.ts | 10 ++ .../javascriptEventPayload.test.ts | 164 ++++++++++++++++++ 5 files changed, 196 insertions(+), 12 deletions(-) create mode 100644 src/domain/compactStringIdentity.ts create mode 100644 tests/acceptance/applications/javascriptEventPayload.test.ts diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index 592276e15..f26c16d1f 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -118,6 +118,16 @@ Use IDs from the selected graph and read the complete endpoint properties; previously stored graphs still support their original IDs. Literal endpoint search, semantic tracing, and version comparison use the preserved values. +Event and listener nodes likewise preserve the complete event name in +`properties.event_name`. Event role keys use the same reserved-prefix string +digest rule, scoped to the emitter; repeated registrations, removals, and +dispatches keep one event per exact emitter/name pair. Long event labels use +`event`, and listener labels use the shorter of `:` and +`:listener`. Dynamic names remain `null` with explicit uncertainty. New analyses +change hashed event IDs and longer event/listener labels; query the preserved +name or select IDs from the parent graph. Previously stored graphs keep their +original IDs and remain valid trace inputs. + ## Version comparison REA pairs entities only when a tier produces one unique candidate on each side. diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts index 580a4d035..41f480daf 100644 --- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts +++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; -import { digestCanonicalValue } from "../../domain/canonicalDigest.js"; +import { compactStringIdentityKey } from "../../domain/compactStringIdentity.js"; import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js"; import type { JavaScriptStaticAnalysis } from "../../domain/javascript/javascriptStaticAnalysisTypes.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; @@ -163,14 +163,7 @@ const addEndpoint = ( const source = sourceNodeFor(context, input.file.path, input.value.module_key) ?? input.asset; - const digestPrefix = "value-sha256:"; - const valueKey = `${digestPrefix}${digestCanonicalValue(input.value.value, "JavaScript endpoint")}`; - // Reserve the digest prefix so an exact caller value cannot alias a digest key. - const key = - input.value.value.length <= valueKey.length && - !input.value.value.startsWith(digestPrefix) - ? input.value.value - : valueKey; + const key = compactStringIdentityKey(input.value.value); const label = `${input.value.kind} endpoint`; const node = context.accumulator.addNode({ kind: "endpoint", diff --git a/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts b/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts index a8814281f..f54c5c4f3 100644 --- a/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphAsyncProjection.ts @@ -1,3 +1,4 @@ +import { compactStringIdentityKey } from "../../domain/compactStringIdentity.js"; import { createJavaScriptSemanticGraphUnknown } from "../../domain/javascript/javascriptSemanticGraph.js"; import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js"; import type { @@ -21,7 +22,7 @@ export const projectSemanticEvents = ( const eventKey = operation.eventName === null ? operation.eventId - : `${operation.emitterKey}\u0000${operation.eventName}`; + : `${operation.emitterKey}\u0000${compactStringIdentityKey(operation.eventName)}`; const event = eventNodes.get(eventKey) ?? addEventNode(context, operation, eventKey); if (event === null) continue; @@ -59,7 +60,11 @@ const addEventNode = ( kind: "event", roleKey: `event:${eventKey}`, location: operation.eventName === null ? operation.location : null, - label: operation.eventName, + label: + operation.eventName === null || + operation.eventName.length <= "event".length + ? operation.eventName + : "event", functionNodeId: null, properties: { emitter_key: operation.emitterKey, @@ -78,7 +83,9 @@ const addListenerNode = ( label: operation.eventName === null ? operation.method - : `${operation.method}:${operation.eventName}`, + : operation.eventName.length <= "listener".length + ? `${operation.method}:${operation.eventName}` + : `${operation.method}:listener`, functionNodeId: operation.ownerCallableId === null ? null diff --git a/src/domain/compactStringIdentity.ts b/src/domain/compactStringIdentity.ts new file mode 100644 index 000000000..421555a90 --- /dev/null +++ b/src/domain/compactStringIdentity.ts @@ -0,0 +1,10 @@ +import { digestCanonicalValue } from "./canonicalDigest.js"; + +/** Retain short exact string keys or commit their value in a reserved digest namespace. */ +export const compactStringIdentityKey = (value: string): string => { + const prefix = "value-sha256:"; + const digestKey = `${prefix}${digestCanonicalValue(value, "String identity")}`; + return value.length <= digestKey.length && !value.startsWith(prefix) + ? value + : digestKey; +}; diff --git a/tests/acceptance/applications/javascriptEventPayload.test.ts b/tests/acceptance/applications/javascriptEventPayload.test.ts new file mode 100644 index 000000000..c4689250d --- /dev/null +++ b/tests/acceptance/applications/javascriptEventPayload.test.ts @@ -0,0 +1,164 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { createHash } from "node:crypto"; +import { 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 { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +cliTest( + "retains large event names and emitter-scoped listener ownership through CLI and stdio MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-event-payload-"); + const name = "payload/ğ".repeat(80_000); + const lookalike = `value-sha256:${createHash("sha256").update(JSON.stringify(name)).digest("hex")}`; + const source = [ + 'import {EventEmitter} from "node:events";', + "const bus = new EventEmitter(); const other = new EventEmitter(); const handler = () => {};", + `bus.on(${JSON.stringify(name)}, handler);`, + `bus.emit(${JSON.stringify(name)});`, + `bus.off(${JSON.stringify(name)}, handler);`, + `bus.on(${JSON.stringify(lookalike)}, handler); bus.emit(${JSON.stringify(lookalike)});`, + 'bus.on("ok", handler); bus.emit("ok"); other.on("ok", handler); other.emit("ok");', + "bus.on(getEventName(), handler);", + ].join("\n"); + await writeFile(join(root, "main.js"), source); + const cliResponse = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + timeoutMs: 60_000, + }); + expect(cliResponse.exitCode).toBe(0); + const cliEvidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(cliResponse.json); + const client = new Client({ name: "event-payload-e2e", 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 response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + expect(response.isError).not.toBe(true); + const evidence = toolContract( + "analyze_javascript_application", + ).outputSchema.parse(response.structuredContent); + expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); + const text = response.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + expect( + toolContract("analyze_javascript_application").outputSchema.parse( + JSON.parse(text.text), + ).evidence_id, + ).toBe(evidence.evidence_id); + const graph = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ).semantic_graph; + const events = graph.nodes.filter((node) => node.kind === "event"); + const selected = events.filter( + (node) => node.properties.event_name === name, + ); + expect(selected).toHaveLength(1); + const event = selected[0]; + if (event === undefined) throw new Error("Complete event was lost"); + const listeners = graph.nodes.filter( + (node) => + node.kind === "listener" && node.properties.event_name === name, + ); + expect(new Set(listeners.map((node) => node.properties.method))).toEqual( + new Set(["on", "off"]), + ); + const listenerIds = new Set(listeners.map((node) => node.node_id)); + expect( + graph.relations + .filter( + (relation) => + relation.source_node_id === event.node_id && + listenerIds.has(relation.target_node_id), + ) + .map((relation) => relation.relation), + ).toEqual( + expect.arrayContaining(["registers-listener", "removes-listener"]), + ); + const lookalikeEvent = events.find( + (node) => node.properties.event_name === lookalike, + ); + expect(lookalikeEvent).toBeDefined(); + expect(lookalikeEvent?.node_id).not.toBe(event.node_id); + const shortEvents = events.filter( + (node) => node.properties.event_name === "ok", + ); + expect(shortEvents).toHaveLength(2); + expect( + new Set(shortEvents.map((node) => node.properties.emitter_key)).size, + ).toBe(2); + expect( + shortEvents.every( + (node) => + node.label === "ok" && node.identity.role_key.endsWith("\0ok"), + ), + ).toBe(true); + const dynamic = events.find( + (node) => node.properties.event_name === null, + ); + expect(dynamic?.label).toBeNull(); + expect( + graph.unknowns.some( + (unknown) => + unknown.node_id === dynamic?.node_id && unknown.family === "event", + ), + ).toBe(true); + const traceResponse = await client.callTool({ + name: "trace_javascript_semantics", + arguments: { + application: { + kind: "retained-evidence", + evidence_id: evidence.evidence_id, + }, + query: { + seed: { kind: "event", name }, + direction: "forward-influence", + }, + }, + }); + expect(traceResponse.isError).not.toBe(true); + const traceEvidence = toolContract( + "trace_javascript_semantics", + ).outputSchema.parse(traceResponse.structuredContent); + const trace = javaScriptSemanticTraceResultSchema.parse( + traceEvidence.normalized_result, + ); + expect(new Set(trace.seed_node_ids)).toEqual( + new Set([event.node_id, ...listenerIds]), + ); + expect( + trace.nodes + .filter((node) => listenerIds.has(node.node_id)) + .map((node) => node.properties.event_name), + ).toEqual(listeners.map(() => name)); + await client.ping(); + } finally { + await client.close(); + await transport.close(); + } + }, + 120_000, +); From c29931ce81dc530d2623ec992714a70b1f3e50e4 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:25:00 -0400 Subject: [PATCH 149/189] fix(javascript): scan direct returns without recursive stack growth Use the shared AST child enumeration with an explicit stack, preserving return order and nested callable boundaries. Refs #1065. Co-authored-by: rudycelekli <47457359+rudycelekli@users.noreply.github.com> Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> --- .../javascript/javascriptSemanticReturns.ts | 14 +++--- .../javascriptApplicationDeepReturns.test.ts | 44 +++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 tests/boundary/filesystem/javascriptApplicationDeepReturns.test.ts diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts index bb931fba5..44cbbea5b 100644 --- a/src/domain/javascript/javascriptSemanticReturns.ts +++ b/src/domain/javascript/javascriptSemanticReturns.ts @@ -131,15 +131,17 @@ const directReturnExpressions = (callable: t.Node): ReturnExpression[] => { return [{ node: callable.body, location: range(callable.body) }]; if (!t.isFunction(callable)) return []; const output: ReturnExpression[] = []; - const visit = (node: t.Node): void => { - if (t.isFunction(node) || t.isClass(node)) return; + const pending = childNodes(callable.body).reverse(); + while (pending.length > 0) { + const node = pending.pop(); + if (node === undefined || t.isFunction(node) || t.isClass(node)) continue; if (t.isReturnStatement(node)) { output.push({ node: node.argument ?? null, location: range(node) }); - return; + continue; } - for (const child of childNodes(node)) visit(child); - }; - for (const child of childNodes(callable.body)) visit(child); + // Reverse children so the explicit stack retains source-tree order. + for (const child of childNodes(node).reverse()) pending.push(child); + } return output; }; diff --git a/tests/boundary/filesystem/javascriptApplicationDeepReturns.test.ts b/tests/boundary/filesystem/javascriptApplicationDeepReturns.test.ts new file mode 100644 index 000000000..32a2d99af --- /dev/null +++ b/tests/boundary/filesystem/javascriptApplicationDeepReturns.test.ts @@ -0,0 +1,44 @@ +import { execFile } from "node:child_process"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +import { expect, it } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +it("analyzes direct returns after deep source without exhausting the default process stack", async () => { + const root = await createTestTempDirectory("rea-deep-direct-returns-"); + await writeFile( + join(root, "app.js"), + `export function render() { object${".property".repeat(20_000)}; function nested() { return "nested"; } class Inner { method() { return "method"; } } return "ready"; }`, + ); + const service = new URL( + "../../../dist/application/javascript/JavaScriptApplicationService.js", + import.meta.url, + ).href; + const script = ` + import { analyzeJavaScriptApplication } from ${JSON.stringify(service)}; + const result = await analyzeJavaScriptApplication({ input_path: ${JSON.stringify(root)}, format: "directory" }); + if (!result.ok) throw result.error; + const nodes = result.value.normalized_result.semantic_graph.nodes; + console.log(JSON.stringify(nodes.filter(node => node.kind === "return-site").map(node => node.function_node_id))); + `; + const { stdout, stderr } = await promisify(execFile)( + process.execPath, + ["--input-type=module", "-e", script], + { + timeout: 10_000, + // Bound the child heap while retaining Node's default stack size. + env: { + HOME: root, + TMPDIR: root, + NODE_OPTIONS: "--max-old-space-size=768", + }, + }, + ); + expect(stderr).toBe(""); + const owners: unknown = JSON.parse(stdout); + expect(owners).toHaveLength(3); + expect(new Set(Array.isArray(owners) ? owners : []).size).toBe(3); +}); From 6375ccaf04b4835cc67080ee1ecd91d1fc46645c Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:35:50 -0700 Subject: [PATCH 150/189] perf(native): record macOS command provenance once in its Evidence (#1430) inspect_macho, inspect_signature, inspect_plist, list_architectures and demangle_swift already return their command provenance inside the normalized result. The provider also copied the same array into raw_result, so every response carried it twice. raw_result now stays null, as docs/mcp-contracts.md describes for results without a distinct provider representation. Co-authored-by: Claude Opus 5.5 --- src/native/NativeMacOSProvider.ts | 6 --- src/native/NativeMachoInspection.ts | 2 - .../providers/native/nativeProvider.test.ts | 37 +++++++++++++++++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index 12c94814f..d63db2506 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -233,7 +233,6 @@ class NativeMacOSClient implements AnalysisClient { return observation.ok ? ok( createAnalysisExecution(observation.value.result, IDENTITY, { - rawResult: { provenance: observation.value.provenance }, limitations: observation.value.limitations, locations: observation.value.locations, }), @@ -317,7 +316,6 @@ class NativeMacOSClient implements AnalysisClient { }); return ok({ result: jsonValueSchema.parse(result), - provenance, limitations: [], locations: architectureLocations(result.architectures.items), }); @@ -351,7 +349,6 @@ class NativeMacOSClient implements AnalysisClient { }); return ok({ result: jsonValueSchema.parse(result), - provenance, limitations: [], locations: [], }); @@ -448,7 +445,6 @@ class NativeMacOSClient implements AnalysisClient { }); return ok({ result: jsonValueSchema.parse(result), - provenance, limitations: result.limitations, locations: [], }); @@ -611,7 +607,6 @@ class NativeMacOSClient implements AnalysisClient { }); return ok({ result: jsonValueSchema.parse(result), - provenance, limitations: parsed.value.limitations, locations: [{ kind: "artifact-path", path: plist.value }], }); @@ -659,7 +654,6 @@ class NativeMacOSClient implements AnalysisClient { interface NativeObservation { readonly result: JsonValue; - readonly provenance: readonly NativeCommandInvocation[]; readonly limitations: readonly string[]; readonly locations: readonly EvidenceLocation[]; } diff --git a/src/native/NativeMachoInspection.ts b/src/native/NativeMachoInspection.ts index 417b43fef..2ef2c95ae 100644 --- a/src/native/NativeMachoInspection.ts +++ b/src/native/NativeMachoInspection.ts @@ -15,7 +15,6 @@ import { parseOtoolLoadCommands } from "./parsers/otool.js"; interface NativeMachoObservation { readonly result: JsonValue; - readonly provenance: readonly NativeCommandInvocation[]; readonly limitations: readonly string[]; readonly locations: readonly EvidenceLocation[]; } @@ -116,7 +115,6 @@ export const inspectNativeMacho = async ( : normalized; return ok({ result: jsonValueSchema.parse(result), - provenance: result.provenance, limitations: result.limitations, locations: fileOffsetLocations(result, segmentOffset), }); diff --git a/tests/boundary/providers/native/nativeProvider.test.ts b/tests/boundary/providers/native/nativeProvider.test.ts index d5be920ba..70a3b06ad 100644 --- a/tests/boundary/providers/native/nativeProvider.test.ts +++ b/tests/boundary/providers/native/nativeProvider.test.ts @@ -552,6 +552,43 @@ describe("native macOS provider inspection", () => { }); }); +describe("native macOS provider raw results", () => { + it("records command provenance once, in the normalized result", async () => { + directory = await createTestTempDirectory("rea-native-"); + const app = join(directory, "Fixture.app"); + const executable = join(app, "Contents/MacOS/Fixture"); + await mkdir(join(app, "Contents/MacOS"), { recursive: true }); + await writeFile(executable, "fixture"); + await writeFile(join(app, "Contents/Info.plist"), "fixture"); + const client = new NativeMacOSProvider( + {}, + new FixtureRunner(), + "darwin", + ).createClient(await nativeMachoTargetForFile(executable, app)); + const requests: readonly (readonly [ + Parameters[0], + Parameters[1], + ])[] = [ + ["inspect_macho", {}], + ["list_architectures", {}], + ["inspect_signature", {}], + ["inspect_plist", {}], + ["demangle_swift", { symbols: ["$s4Test3fooyyF", "plain_symbol"] }], + ]; + + for (const [operation, parameters] of requests) { + const execution = await client.execute(operation, parameters); + if (!execution.ok) throw execution.error; + expect(execution.value.rawResult, operation).toBeNull(); + expect(execution.value.result, operation).toMatchObject({ + provenance: expect.arrayContaining([ + expect.objectContaining({ tool: expect.any(String) }), + ]), + }); + } + }); +}); + describe("native plist defaults for iOS-style bundles", () => { it("defaults to the Info.plist the bundle program was resolved from", async () => { directory = await createTestTempDirectory("rea-native-flat-"); From 0b9815b6e7080081d8fd426ad9710aee36761afa Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:38:52 -0700 Subject: [PATCH 151/189] docs(skill): save CLI application Evidence and read a summary view (#1429) The skill's CLI fallback printed the complete application Evidence to stdout. A real ASAR produces hundreds of megabytes (334 MB for Obsidian), which an agent then reads into its context. Save the Evidence to a file and project a summary or module page with inspect-analysis-view instead. Co-authored-by: Claude Opus 5.5 --- docs/cli.md | 17 +++++++++++++++++ skill-src/reverse-engineer-anything/SKILL.md | 19 +++++++++++++------ src/generatedPackageMetadata.ts | 2 +- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 2a9863c1e..245251a28 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -20,6 +20,23 @@ files when neither `--provider` nor `--snapshot` is supplied. See [JavaScript artifact reconstruction](javascript-artifact-reconstruction.md) for results, integrity checks and coverage. +The complete application Evidence can be hundreds of megabytes for a real +application. When an agent or a person reads the result, save it to a file and +project a summary, a module page or one module from the saved Evidence: + +```bash +rea analyze-javascript-application /absolute/path/to/app --json > app-evidence.json +jq -c '{source: {kind: "inline", evidence: .}, view: {kind: "summary"}}' app-evidence.json > app-view.json +rea inspect-analysis-view app-view.json +``` + +For example, a 334 MB Obsidian application Evidence file yields a summary view +of about 10 KB. Replace the view with +`{"kind": "page", "collection": "modules", "offset": 0, "limit": 32}` for a +module page. See +[JavaScript application workflows](javascript-application-workflows.md) for +views, feature traces and comparisons that take the same saved Evidence. + ## Native analysis Configure [Hopper or Ghidra](installation.md#hopper), or the diff --git a/skill-src/reverse-engineer-anything/SKILL.md b/skill-src/reverse-engineer-anything/SKILL.md index d1650f26e..3eaa239b8 100644 --- a/skill-src/reverse-engineer-anything/SKILL.md +++ b/skill-src/reverse-engineer-anything/SKILL.md @@ -2,7 +2,7 @@ name: reverse-engineer-anything description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. metadata: - version: "34" + version: "35" --- # REA @@ -62,13 +62,20 @@ with a version-pinned `rea-agents` package or continue through the CLI. A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is: ```bash -npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json +npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json > app-evidence.json +jq -c '{source: {kind: "inline", evidence: .}, view: {kind: "summary"}}' app-evidence.json > app-view.json +npx -y rea-agents@latest inspect-analysis-view app-view.json ``` -No MCP registration or native engine is required. Read the returned Evidence, -graph, limitations, and unknowns with the same care as an MCP result; the CLI -returns the Evidence record directly. This fallback does not establish that -MCP is configured. Native CLI tasks still require their selected engine. +No MCP registration or native engine is required. The CLI returns the complete +Evidence record directly, and a real application can produce hundreds of +megabytes, so save it to a file rather than reading it into context. Start from +the summary view, then request a module page +(`{"kind": "page", "collection": "modules", "offset": 0, "limit": 32}`) or one +module the same way, or pass the saved Evidence inline to +`trace-application-feature`. Read graph, limitations, and unknowns with the +same care as an MCP result. This fallback does not establish that MCP is +configured. Native CLI tasks still require their selected engine. ## Route the target first diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index 29177bf02..468117b05 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -5,5 +5,5 @@ export const PACKAGE_METADATA = { serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", - skillVersion: "34", + skillVersion: "35", } as const; From dc5af6d68f74155d32a0be957c88afb0ee4be699 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:49:09 +0800 Subject: [PATCH 152/189] perf(mcp): reuse output validators across catalog refreshes (#1433) Advertise content- and dialect-bound identities for self-contained output schemas so the SDK can reuse unchanged Ajv validators after complete tools/list refreshes. Preserve explicit IDs and relative reference bases. Verify changed schemas, availability transitions, reconnects, numeric and selector constraints, explicit IDs, relative references, and advertised dialects through the pinned SDK boundaries. Refs #1065, #723 --- docs/mcp-contracts.md | 7 ++ src/contracts/toolOutputReferences.test.ts | 58 ++++++++++ src/contracts/toolSchemaMetadata.ts | 44 ++++++- .../boundary/mcp/outputValidatorReuse.test.ts | 108 ++++++++++++++++++ 4 files changed, 213 insertions(+), 4 deletions(-) create mode 100644 tests/boundary/mcp/outputValidatorReuse.test.ts diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 7bf2fb76c..70d843335 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -36,6 +36,13 @@ after SDK conversion and check advertised validation and actual calls. Individual model APIs can impose additional nesting limits; complete producer captures can exceed ten structural levels. +Self-contained output schemas advertise a content-bound `$id`, including their +declared dialect. SDK validators can reuse compiled schemas across complete +catalog refreshes and equivalent tool outputs; changing the schema changes its +identity. Explicit schema IDs and relative external reference bases are +preserved. This keeps every tool and validation rule in discovery and does not +change the SDK's catalog invalidation or availability checks. + `compare_web_captures` accepts exactly one of two input shapes: - Passive: `before` and `after` each contain `inspection`, the complete diff --git a/src/contracts/toolOutputReferences.test.ts b/src/contracts/toolOutputReferences.test.ts index 70c1f5ea5..cda49f1d5 100644 --- a/src/contracts/toolOutputReferences.test.ts +++ b/src/contracts/toolOutputReferences.test.ts @@ -1,11 +1,69 @@ import { Ajv } from "ajv"; import { Ajv2020 } from "ajv/dist/2020.js"; +import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv"; import { expect, it } from "vitest"; import { z } from "zod"; import { toolContract } from "./toolContracts.js"; import { toolOutputSchemaWithMetadata } from "./toolSchemaMetadata.js"; +it("keeps dialect-specific validators distinct after JSON schema serialization", () => { + const contract = { + ...toolContract("binary_session"), + outputSchema: z.strictObject({ value: z.number().int().min(1).max(8) }), + }; + const output = toolOutputSchemaWithMetadata(contract); + const provider = new AjvJsonSchemaValidator(); + for (const target of ["draft-2020-12", "draft-07"] as const) { + const projected = output["~standard"].jsonSchema.output({ target }); + const parsed = z + .record(z.string(), z.unknown()) + .parse(JSON.parse(JSON.stringify(projected))); + const validate = provider.getValidator(parsed); + expect(validate({ value: 8 }).valid).toBe(true); + expect(validate({ value: 9 }).valid).toBe(false); + expect(validate({ value: 1.5 }).valid).toBe(false); + } +}); + +it("preserves explicit schema identity and relative reference resolution", () => { + const value = z.string(); + const canonical = z.strictObject({ value }); + const contract = { + ...toolContract("binary_session"), + outputSchema: canonical, + }; + const projected = toolOutputSchemaWithMetadata(contract)[ + "~standard" + ].jsonSchema.output({ + target: "draft-2020-12", + libraryOptions: { + override: (context: { + readonly zodSchema: unknown; + readonly jsonSchema: Record; + }) => { + if (context.zodSchema !== value) return; + delete context.jsonSchema.type; + context.jsonSchema.$ref = "child.json"; + }, + }, + }); + const ajv = new Ajv2020({ strict: false }); + ajv.addSchema({ $id: "child.json", type: "string", minLength: 3 }); + const validate = ajv.compile(projected); + expect(validate({ value: "abc" })).toBe(true); + expect(validate({ value: "ab" })).toBe(false); + + const identified = toolOutputSchemaWithMetadata({ + ...contract, + outputSchema: canonical.meta({ $id: "https://example.test/result" }), + })["~standard"].jsonSchema.output({ target: "draft-2020-12" }); + expect(identified.$id).toBe("https://example.test/result"); + const explicit = ajv.compile(identified); + expect(explicit({ value: "abc" })).toBe(true); + expect(explicit({ value: 1 })).toBe(false); +}); + it.each(["draft-2020-12", "draft-07"] as const)( "preserves refined numeric bounds and strict repeated objects through %s references", (target) => { diff --git a/src/contracts/toolSchemaMetadata.ts b/src/contracts/toolSchemaMetadata.ts index f2d395ece..8f43f1708 100644 --- a/src/contracts/toolSchemaMetadata.ts +++ b/src/contracts/toolSchemaMetadata.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import type { ToolContract } from "./toolContractTypes.js"; import { presentInputJsonSchema } from "./inputSchemaPresentation.js"; +import { digestCanonicalValue } from "../domain/canonicalDigest.js"; const PROPERTY_DESCRIPTIONS: Readonly> = { addresses: "Ordered provider-normalized procedure addresses to analyze.", @@ -69,20 +70,55 @@ export const toolInputSchemaWithMetadata = ( }, ); -/** Share repeated output definitions without changing canonical validation. */ +/** Share output definitions and content-bound validator identities on the wire. */ export const toolOutputSchemaWithMetadata = ( contract: Contract, ): Contract["outputSchema"] => withAdvertisedJsonSchema( contract.outputSchema, "output", - (project) => (options) => - project({ + (project) => (options) => { + const shared = project({ ...options, libraryOptions: { reused: "ref", ...options.libraryOptions }, - }), + }); + // An explicit ID owns the reference base. Relative external references + // also depend on that base, so leave those projections unchanged. + if ("$id" in shared || hasRelativeSchemaReference(shared)) return shared; + return { + ...shared, + $id: `urn:rea:tool-output:sha256:${digestCanonicalValue( + { target: options.target, schema: shared }, + "Tool output schema", + )}`, + }; + }, ); +const hasRelativeSchemaReference = ( + schema: Record, +): boolean => { + const pending: unknown[] = [schema]; + const visited = new WeakSet(); + while (pending.length > 0) { + const current = pending.pop(); + if (current === null || typeof current !== "object" || visited.has(current)) + continue; + visited.add(current); + for (const [key, value] of Object.entries(current)) { + if ( + ["$id", "$ref", "$dynamicRef", "$recursiveRef"].includes(key) && + typeof value === "string" && + !value.startsWith("#") && + !URL.canParse(value) + ) + return true; + if (value !== null && typeof value === "object") pending.push(value); + } + } + return false; +}; + const withAdvertisedJsonSchema = ( canonical: Schema, io: "input" | "output", diff --git a/tests/boundary/mcp/outputValidatorReuse.test.ts b/tests/boundary/mcp/outputValidatorReuse.test.ts new file mode 100644 index 000000000..256c29d58 --- /dev/null +++ b/tests/boundary/mcp/outputValidatorReuse.test.ts @@ -0,0 +1,108 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { McpServer } from "@modelcontextprotocol/server"; +import { expect, it } from "vitest"; +import { z } from "zod"; + +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { toolOutputSchemaWithMetadata } from "../../../src/contracts/toolSchemaMetadata.js"; + +const advertised = < + Schema extends z.ZodType>>, +>( + schema: Schema, +): Schema => + toolOutputSchemaWithMetadata({ + ...toolContract("binary_session"), + outputSchema: schema, + }); + +const connect = async (server: McpServer, client: Client): Promise => { + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); +}; + +it("validates changed schemas after catalog refreshes and availability changes", async () => { + const client = new Client({ name: "output-reuse-test", version: "1" }); + const server = new McpServer({ name: "output-reuse-fixture", version: "1" }); + const schema = advertised(z.strictObject({ state: z.literal("ready") })); + let state = "ready"; + const selected = server.registerTool( + "selected", + { inputSchema: z.strictObject({}), outputSchema: schema }, + () => ({ content: [], structuredContent: { state } }), + ); + server.registerTool( + "equivalent", + { inputSchema: z.strictObject({}), outputSchema: schema }, + () => ({ content: [], structuredContent: { state: "ready" } }), + ); + try { + await connect(server, client); + await client.listTools(); + expect( + (await client.callTool({ name: "selected" })).structuredContent, + ).toEqual({ + state: "ready", + }); + await client.listTools(); + await client.callTool({ name: "equivalent" }); + + selected.update({ + outputSchema: advertised(z.strictObject({ state: z.literal("updated") })), + }); + state = "updated"; + await client.listTools(); + expect( + (await client.callTool({ name: "selected" })).structuredContent, + ).toEqual({ + state: "updated", + }); + selected.disable(); + const unavailable = await client.listTools(); + expect(unavailable.tools.some((tool) => tool.name === "selected")).toBe( + false, + ); + await expect(client.callTool({ name: "selected" })).rejects.toThrow( + /not found|disabled/iu, + ); + await client.callTool({ name: "equivalent" }); + selected.enable(); + await client.listTools(); + await client.callTool({ name: "selected" }); + } finally { + await Promise.allSettled([client.close(), server.close()]); + } +}); + +it("uses the new server's schema after reconnecting the client", async () => { + const client = new Client({ name: "output-reconnect-test", version: "1" }); + const servers: McpServer[] = []; + try { + for (const state of ["first", "second"]) { + const server = new McpServer({ name: `fixture-${state}`, version: "1" }); + servers.push(server); + server.registerTool( + "selected", + { + inputSchema: z.strictObject({}), + outputSchema: advertised(z.strictObject({ state: z.literal(state) })), + }, + () => ({ content: [], structuredContent: { state } }), + ); + await connect(server, client); + await client.listTools(); + expect( + (await client.callTool({ name: "selected" })).structuredContent, + ).toEqual({ state }); + await client.close(); + await server.close(); + } + } finally { + await Promise.allSettled([ + client.close(), + ...servers.map((server) => server.close()), + ]); + } +}); From 0a14ca41b46e42d36d46ba07384ff13a7a97456d Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:00:11 +0800 Subject: [PATCH 153/189] fix(javascript): preserve effects through yielded array references (#1437) --- .../javascript/javascriptSemanticAnalysis.ts | 20 ++- .../javascriptSemanticIterationSources.ts | 12 +- .../javascriptSemanticMemberMutations.ts | 15 +- .../javascriptIterationAliases.test.ts | 145 ++++++++++++++++++ 4 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 tests/acceptance/applications/javascriptIterationAliases.test.ts diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 5a873429e..1cf53fb31 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -565,9 +565,21 @@ const bindAssignment = ( else if (t.isForOfStatement(node) || t.isForInStatement(node)) for (const pattern of t.isVariableDeclaration(node.left) ? node.left.declarations.map(({ id }) => id) - : [node.left]) + : [node.left]) { for (const identifier of assignedPatternIdentifiers(pattern)) addAssignment(identifier, node, scope, state); + if (t.isForOfStatement(node)) + // Keep the loop value unknown, but preserve references yielded into + // each bound slot so writes/escapes can reach their iterable origins. + bindPattern({ + pattern, + initializer: node, + scope, + state, + mutable: true, + referenceOnly: true, + }); + } }; const assignedPatternIdentifiers = ( @@ -780,7 +792,11 @@ const bindPattern = (input: BindPatternInput): void => { } if (t.isIdentifier(pattern)) { if (referenceOnly) { - const binding = scope.bindings.get(pattern.name); + const binding = resolveSemanticBindingFromScope( + scope, + pattern.name, + state, + ); if (binding !== undefined && initializer !== null) binding.referenceInitializers.push({ node: initializer, diff --git a/src/domain/javascript/javascriptSemanticIterationSources.ts b/src/domain/javascript/javascriptSemanticIterationSources.ts index 1b9e7d714..c83eb94ad 100644 --- a/src/domain/javascript/javascriptSemanticIterationSources.ts +++ b/src/domain/javascript/javascriptSemanticIterationSources.ts @@ -8,8 +8,9 @@ interface IterationSourceValue { readonly projection: readonly (string | number | null)[]; } -/** An implicit iterator receiver, with guards for destructuring defaults. */ +/** An iterator receiver or yielded reference store, with default guards. */ export interface SemanticIterationSource extends IterationSourceValue { + readonly kind: "iteration" | "reference-store"; readonly mutation: t.Node; readonly fallbackSources?: readonly IterationSourceValue[]; readonly requiredSources?: readonly IterationSourceValue[]; @@ -30,8 +31,10 @@ const add = ( source: IterationSourceValue, mutation: t.Node, guards: SourceGuards, + kind: SemanticIterationSource["kind"] = "iteration", ): void => { sources.push({ + kind, node: source.node, projection: source.projection, mutation, @@ -66,6 +69,13 @@ const visit = ( guards: SourceGuards = {}, ): void => { const { sources, mutation } = context; + if (t.isForOfStatement(mutation) && t.isMemberExpression(pattern)) { + // Storing a yielded reference in a property has no lexical loop binding. + // Preserve its escape rather than assuming later writes cannot reach it. + if (source !== undefined) + add(sources, source, mutation, guards, "reference-store"); + return; + } if (t.isTSParameterProperty(pattern)) { visit(context, pattern.parameter, source, guards); return; diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 21a6aded0..4e4ea7b8b 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -324,7 +324,7 @@ export const collectSemanticMemberMutations = ( bindings: new Set(), effect: "escape", originAt: source.mutation, - iterationOnly: true, + iterationOnly: source.kind === "iteration", }); if (t.isAssignmentExpression(node)) markTarget(node.left, node); else if (t.isUpdateExpression(node)) markTarget(node.argument, node); @@ -369,6 +369,19 @@ export const collectSemanticMemberMutations = ( const { initializer } = reference; if (referenceSourcesInactive(initializer, state)) pendingReferences.push(reference); + else if (t.isForOfStatement(initializer.node)) + deferIterable({ + node: initializer.node.right, + projection: [], + path: [null, ...reference.path], + fallbackPath: [], + bindings: reference.bindings, + effect: reference.effect, + originAt: initializer.node, + ...(reference.mutation === undefined + ? {} + : { mutation: reference.mutation }), + }); else if ( initializer.copyKind === "array-rest" && initializer.copyProjectionOffset !== undefined diff --git a/tests/acceptance/applications/javascriptIterationAliases.test.ts b/tests/acceptance/applications/javascriptIterationAliases.test.ts new file mode 100644 index 000000000..103995480 --- /dev/null +++ b/tests/acceptance/applications/javascriptIterationAliases.test.ts @@ -0,0 +1,145 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { 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 { projectedExportReturnShapesSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +const source = [ + "export function inline() { const shared = { x: 1, keep: 7 }; for (const t of [shared]) t.x = 2; return { x: shared.x, keep: shared.keep }; }", + "export function named() { const shared = { x: 1 }; const arr = [shared]; for (const t of arr) t.x = 2; return shared.x; }", + "export function declaredVar() { const shared = { x: 1 }; for (var t of [shared]) t.x = 2; return shared.x; }", + "export function assigned() { const shared = { x: 1 }; let t; for (t of [shared]) t.x = 2; return shared.x; }", + "export function assignedDestructured() { const shared = { x: 1 }; let t; for ({child: t} of [{child: shared}]) t.x = 2; return shared.x; }", + "export function declaredVarDestructured() { const shared = { x: 1 }; for (var {child: t} of [{child: shared}]) t.x = 2; return shared.x; }", + "export function memberTarget() { const shared = { x: 1 }; const holder = {}; for (holder.item of [shared]) holder.item.x = 2; return shared.x; }", + "export function memberPattern() { const shared = { x: 1 }; const holder = {}; for ({child: holder.item} of [{child: shared}]) holder.item.x = 2; return shared.x; }", + "export function destructured() { const shared = { x: 1 }; for (const {child: t} of [{child: shared}]) t.x = 2; return shared.x; }", + "export function arrayDestructured() { const shared = { x: 1 }; for (const [t] of [[shared]]) t.x = 2; return shared.x; }", + "export function spread() { const shared = { x: 1 }; const arr = [shared]; for (const t of [...arr]) t.x = 2; return shared.x; }", + "export function objectRestChild() { const shared = { x: 1 }; for (const {...t} of [{child: shared}]) t.child.x = 2; return shared.x; }", + "export function arrayRestChild() { const shared = { x: 1 }; for (const [...t] of [[shared]]) t[0].x = 2; return shared.x; }", + "export function defaultChild() { const shared = { x: 1 }; for (const {child: t = shared} of [{}]) t.x = 2; return shared.x; }", + "export function updated() { const shared = { x: 1 }; for (const t of [shared]) t.x++; return shared.x; }", + "export function deleted() { const shared = { x: 1 }; for (const t of [shared]) delete t.x; return shared.x; }", + "export function escaped() { const shared = { x: 1 }; for (const t of [shared]) consume(t); return shared.x; }", + "export async function awaited() { const shared = { x: 1 }; for await (const t of [shared]) t.x = 2; return shared.x; }", + "export function indexed() { const shared = { x: 1 }; const arr = [shared]; for (let i = 0; i < arr.length; i++) { const t = arr[i]; t.x = 2; } return shared.x; }", + "export function copyWrite() { const shared = { x: 1 }; for (const {...t} of [shared]) t.x = 2; return shared.x; }", + "export function noWrite() { const shared = { x: 1 }; for (const t of [shared]) { const read = t.x; } return shared.x; }", + "export function empty() { const shared = { x: 1 }; for (const t of []) t.x = 2; return shared.x; }", + "export function keys() { const shared = { x: 1 }; for (const key in [shared]) { const read = key; } return shared.x; }", + "export function shadowed() { const t = { x: 1 }; const shared = { x: 3 }; for (const t of [shared]) t.x = 2; return t.x; }", +].join("\n"); + +const assertReturns = (value: unknown): void => { + const analysis = javascriptApplicationAnalysisResultSchema.parse(value); + const projections = analysis.graph.nodes + .flatMap(({ observations }) => observations) + .filter( + ({ properties }) => properties.semantic_role === "export-return-shapes", + ) + .map(({ properties }) => + projectedExportReturnShapesSchema.parse(properties), + ); + const fields = (name: string) => { + const projection = projections.find( + ({ exported_name }) => exported_name === name, + ); + if (projection === undefined) throw new Error(`Missing export ${name}`); + expect(projection.return_shape_coverage).toMatchObject({ + status: "complete", + projection_complete: true, + }); + return projection.static_return_shapes.flatMap(({ fields }) => fields); + }; + expect(fields("inline")).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: "/x", state: "unknown" }), + expect.objectContaining({ path: "/keep", state: "literal", value: 7 }), + ]), + ); + for (const name of [ + "named", + "declaredVar", + "assigned", + "assignedDestructured", + "declaredVarDestructured", + "memberTarget", + "memberPattern", + "destructured", + "arrayDestructured", + "spread", + "objectRestChild", + "arrayRestChild", + "defaultChild", + "updated", + "deleted", + "escaped", + "awaited", + "indexed", + ]) + expect(fields(name), name).toContainEqual( + expect.objectContaining({ path: "", state: "unknown" }), + ); + for (const name of ["copyWrite", "noWrite", "empty", "keys", "shadowed"]) + expect(fields(name), name).toContainEqual( + expect.objectContaining({ path: "", state: "literal", value: 1 }), + ); +}; + +cliTest( + "preserves yielded-object mutation uncertainty through CLI and stdio MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-iteration-aliases-"); + await writeFile(join(root, "app.js"), source); + const cliResponse = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + }); + expect(cliResponse.exitCode).toBe(0); + const contract = toolContract("analyze_javascript_application"); + const cliEvidence = contract.outputSchema.parse(cliResponse.json); + assertReturns(cliEvidence.normalized_result); + const client = new Client({ name: "iteration-aliases-e2e", 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 response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + expect(response.isError).not.toBe(true); + const evidence = contract.outputSchema.parse(response.structuredContent); + expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); + assertReturns(evidence.normalized_result); + const text = response.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + assertReturns( + contract.outputSchema.parse(JSON.parse(text.text)).normalized_result, + ); + await client.ping(); + } finally { + await client.close(); + await transport.close(); + } + }, + 120_000, +); From ce16f7bc951180b68707fc8cec7e20a0511bb5b3 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:05:12 +0800 Subject: [PATCH 154/189] test(native): verify macOS provenance through real CLI and MCP Verify five native operations through the public CLI and real SDK stdio MCP using a source-built macOS fixture. Retain normalized provenance, response parity and unchanged input bytes. Refs #1430, #1065, #723. --- scripts/verify/apple/macos-bundle.mjs | 3 + scripts/verify/apple/native-provenance.mjs | 71 ++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 scripts/verify/apple/native-provenance.mjs diff --git a/scripts/verify/apple/macos-bundle.mjs b/scripts/verify/apple/macos-bundle.mjs index c10abcb2e..e2a130842 100644 --- a/scripts/verify/apple/macos-bundle.mjs +++ b/scripts/verify/apple/macos-bundle.mjs @@ -17,6 +17,7 @@ import { import { verifyDyldEnvironment } from "./dyld-environment.mjs"; import { verifyDylibResolution } from "./macos-dylib-e2e.mjs"; import { verifyMachOOccurrences } from "./macho-occurrences.mjs"; +import { verifyNativeProvenance } from "./native-provenance.mjs"; const exec = promisify(execFile); @@ -69,6 +70,7 @@ const EXPECTED_BUNDLES = [ let report; try { const { app, executable } = await buildMacosBundleFixture(root); + const nativeProvenance = await verifyNativeProvenance(app, executable); const machoOccurrences = await verifyMachOOccurrences(app, executable); const zip = join(root, "MacFixture.zip"); await exec("/usr/bin/ditto", ["-c", "-k", "--keepParent", app, zip]); @@ -166,6 +168,7 @@ try { containers: containers.map(({ format }) => format), bundles: EXPECTED_BUNDLES.length, dmg_detached: true, + native_provenance: nativeProvenance, macho_occurrences: machoOccurrences, dylib_resolution: dylibs, dyld_environment: dyldEnvironment, diff --git a/scripts/verify/apple/native-provenance.mjs b/scripts/verify/apple/native-provenance.mjs new file mode 100644 index 000000000..ad7bf6cc1 --- /dev/null +++ b/scripts/verify/apple/native-provenance.mjs @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; + +import { toolContract } from "../../../dist/contracts/toolContracts.js"; +import { + artifactCliEvidence, + withArtifactMcp, +} from "../../lib/artifact-e2e.mjs"; + +/** Inspect the compiled bundle with real native utilities through both adapters. */ +export async function verifyNativeProvenance(app, executable) { + const original = await readFile(executable); + const sha256 = createHash("sha256").update(original).digest("hex"); + const symbols = ["$s4main3FooV", "plain_symbol"]; + const operations = [ + ["inspect_macho", []], + ["inspect_signature", []], + ["inspect_plist", []], + ["list_architectures", []], + ["demangle_swift", symbols], + ]; + const observations = []; + await withArtifactMcp(app, async (client) => { + const definitions = new Map( + (await client.listTools()).tools.map((tool) => [tool.name, tool]), + ); + for (const [operation, arguments_] of operations) { + const cli = toolContract(operation).outputSchema.parse( + await artifactCliEvidence( + operation.replaceAll("_", "-"), + app, + arguments_, + ), + ); + const response = await client.callTool( + { + name: operation, + arguments: operation === "demangle_swift" ? { symbols } : {}, + }, + { toolDefinition: definitions.get(operation) }, + ); + assert.notEqual(response.isError, true, JSON.stringify(response)); + const mcp = toolContract(operation).outputSchema.parse( + response.structuredContent, + ); + assert.equal(cli.raw_result, null); + assert.equal(mcp.raw_result, null); + assert.ok(cli.normalized_result.provenance.length > 0); + assert.deepEqual(mcp.normalized_result, cli.normalized_result); + assert.deepEqual( + JSON.parse(response.content.find((item) => item.type === "text").text), + response.structuredContent, + ); + await client.ping(); + observations.push({ + operation, + commands: cli.normalized_result.provenance.length, + cli_bytes: Buffer.byteLength(JSON.stringify(cli)), + mcp_bytes: Buffer.byteLength(JSON.stringify(response)), + }); + } + }); + assert.deepEqual(await readFile(executable), original); + return { + real_native_utilities: true, + target_sha256: sha256, + bytes_unchanged: true, + observations, + }; +} From bb6fa1c6f500c6b6af42f1e3f72bd42c1dce91f6 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:13:05 +0800 Subject: [PATCH 155/189] docs(process): verify independent full-report hashing budgets (#1440) --- docs/process-capture.md | 46 +++++++- .../processFilesystemCoverageAdapters.test.ts | 104 ++++++++++++++++++ 2 files changed, 148 insertions(+), 2 deletions(-) diff --git a/docs/process-capture.md b/docs/process-capture.md index 21f1f5343..1d3d23e7f 100644 --- a/docs/process-capture.md +++ b/docs/process-capture.md @@ -159,8 +159,11 @@ Trace assertions use coverage for the sources they select, so an assertion about complete raw terminal output need not fail because rendered snapshots were omitted. Captures missing `truncation_details` are rejected on import; preserve them as historical files and recapture for current comparisons. -These diagnostics use the existing scenario -budgets; they do not introduce a separate file-hashing budget. +`limits.file_bytes` is already the cumulative whole-file hashing budget, +independent of `limits.output_bytes`, which bounds retained terminal content. +Each filesystem checkpoint starts with a fresh `file_bytes` budget across all +selected roots; it is not a per-file allowance. File contents are read in +64 KiB chunks for hashing and are not embedded in capture Evidence. When the host withholds an unrelated process’s ownership token, REA leaves that process untouched and records its PID and reason in `cleanup.unverified_processes` @@ -176,6 +179,45 @@ as well. A newly started unreadable process can prevent verified cleanup even after the selected command exits. REA preserves this uncertainty and leaves that process untouched. +## Hash a report independently of terminal output + +Select the producer's report directory and give `file_bytes` enough room for +the complete files you need, including other files in those roots. For example, +save this scenario and run `rea capture-process ./scenario.json --json > capture.json`: + +```json +{ + "executable": "node", + "arguments": [ + "-e", + "const fs=require('node:fs');fs.mkdirSync('reports',{recursive:true});fs.writeFileSync('reports/final.json',JSON.stringify({status:'complete',data:'X'.repeat(131072)}));console.log('x'.repeat(8192));" + ], + "working_directory": ".", + "filesystem_observation_paths": ["./reports"], + "limits": { "output_bytes": 1024, "file_bytes": 262144 } +} +``` + +The report exceeds the terminal budget but fits the independent 256 KiB hash +budget. Its complete SHA-256 appears in `normalized_result.files_after` at +`root_0:final.json`; check `truncation_details.filesystem_after` for omissions +and actual bytes hashed. The verbose terminal output is truncated without +preventing the report digest. The same scenario object is the MCP +`capture_process_scenario` input. REA never returns a prefix hash as a full-file +digest: an insufficient remaining budget produces a null digest and an +explicit omission reason. + +A digest binds the complete bytes observed at that checkpoint, not the +producer's notion of a finished report. A stable periodic or running report +can also have a complete digest. Choose the final file and verify the +producer's documented completion marker, exit outcome and settlement +observations before calling it final. `after_settlement` names a filesystem +checkpoint, not a guarantee that an application finished successfully or +that an unobserved writer will never change the file. REA checks opened-file +identity/state around hashing and reports observed changes or unavailable +files; cancellation stops the hash. If an external sealer produces a manifest, +keep its completion claims and digest separate from REA's checkpoint facts. + ## Compare two captures Compare saved capture Evidence with: diff --git a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts index ec7ce5b4c..ff3b118a7 100644 --- a/tests/boundary/process/processFilesystemCoverageAdapters.test.ts +++ b/tests/boundary/process/processFilesystemCoverageAdapters.test.ts @@ -1,4 +1,5 @@ import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; @@ -7,6 +8,7 @@ import { expect, it, onTestFinished } from "vitest"; import { parseEvidence } from "../../../src/domain/evidence.js"; import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js"; import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js"; +import { parseProcessScenario } from "../../../src/domain/process/processScenario.js"; import { createServer } from "../../../src/server/createServer.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -58,6 +60,108 @@ const captureViaMcp = async (scenario: Record) => { return evidence; }; +itWithCaptureCapability.each(["cli", "mcp"] as const)( + "hashes the documented complete report despite omitted terminal output through %s", + async (adapter) => { + const document = await readFile("docs/process-capture.md", "utf8"); + const example = document + .split("## Hash a report independently of terminal output")[1] + ?.match(/```json\n([\s\S]*?)\n```/u)?.[1]; + if (example === undefined) + throw new Error("Missing report capture example"); + const scenario = parseProcessScenario(JSON.parse(example)); + const root = await createTestTempDirectory("rea-full-report-adapter-"); + const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)({ + ...scenario, + executable: process.execPath, + working_directory: root, + filesystem_observation_paths: [join(root, "reports")], + }); + const capture = parseProcessCapture(evidence.normalized_result); + const bytes = await readFile(join(root, "reports", "final.json")); + expect(JSON.parse(bytes.toString())).toEqual({ + status: "complete", + data: "X".repeat(131072), + }); + expect(bytes.length).toBeGreaterThan(scenario.limits.output_bytes); + expect(capture.files_after).toContainEqual( + expect.objectContaining({ + path: "root_0:final.json", + size: bytes.length, + sha256: createHash("sha256").update(bytes).digest("hex"), + }), + ); + expect(capture.truncation_details.filesystem_after).toMatchObject({ + enumeration_truncated: false, + hash_budget_bytes: scenario.limits.file_bytes, + hashed_bytes: bytes.length, + hash_omissions: [], + }); + expect(capture.truncation_details.raw_terminal.retained_bytes).toBeLessThan( + capture.truncation_details.raw_terminal.observed_bytes, + ); + }, + 20_000, +); + +itWithCaptureCapability.each(["cli", "mcp"] as const)( + "accounts for exact cumulative hash budgets independently at each %s checkpoint", + async (adapter) => { + const runCapture = adapter === "cli" ? captureViaCli : captureViaMcp; + for (const shortfall of [0, 1]) { + const root = await createTestTempDirectory("rea-report-cumulative-"); + const periodic = Buffer.from('{"status":"running"}'); + const final = Buffer.from('{"status":"complete"}'); + await writeFile(join(root, "periodic.json"), periodic); + const budget = periodic.length + final.length - shortfall; + const evidence = await runCapture({ + executable: process.execPath, + arguments: [ + "-e", + "require('node:fs').writeFileSync('final.json','{\"status\":\"complete\"}')", + ], + working_directory: root, + filesystem_observation_paths: [root], + limits: { output_bytes: 1, file_bytes: budget }, + }); + const capture = parseProcessCapture(evidence.normalized_result); + expect(capture.truncation_details.filesystem_before).toMatchObject({ + hashed_bytes: periodic.length, + hash_omissions: [], + }); + expect(capture.files_after).toContainEqual( + expect.objectContaining({ + path: "root_0:final.json", + sha256: createHash("sha256").update(final).digest("hex"), + }), + ); + expect(capture.truncation_details.filesystem_after).toMatchObject({ + enumeration_truncated: false, + hashed_bytes: final.length + (shortfall === 0 ? periodic.length : 0), + hash_omissions: + shortfall === 0 + ? [] + : [ + { + path: "root_0:periodic.json", + reason: "file_bytes_budget", + remaining_budget_bytes: periodic.length - 1, + }, + ], + }); + expect( + capture.files_after.find(({ path }) => path === "root_0:periodic.json") + ?.sha256, + ).toBe( + shortfall === 0 + ? createHash("sha256").update(periodic).digest("hex") + : null, + ); + } + }, + 20_000, +); + itWithCaptureCapability.each(["cli", "mcp"] as const)( "reports unknown absence instead of deletion in truncated %s capture Evidence", async (adapter) => { From eeb83f65817819644af8e6fbf8a120227dfb88d4 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:16:44 -0700 Subject: [PATCH 156/189] perf(cli): defer Playwright and isomorphic-git until a command needs them Load browser composition after CLI scenario validation and load Git support only for local reference trees with Git metadata. Preserve default outputs and actual command behavior. Refs #1065. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --- src/application/ReferenceSourceVcsAdapter.ts | 4 +- src/cliBrowserScenarioCommands.ts | 4 +- tests/boundary/cli/cliStartupImports.test.ts | 76 ++++++++++++++++++++ 3 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 tests/boundary/cli/cliStartupImports.test.ts diff --git a/src/application/ReferenceSourceVcsAdapter.ts b/src/application/ReferenceSourceVcsAdapter.ts index 42ab4e738..3ddad25d7 100644 --- a/src/application/ReferenceSourceVcsAdapter.ts +++ b/src/application/ReferenceSourceVcsAdapter.ts @@ -2,8 +2,6 @@ import fs from "node:fs"; import { lstat, readFile } from "node:fs/promises"; import { join, resolve } from "node:path"; -import { resolveRef } from "isomorphic-git"; - export type ReferenceSourceVcsInfo = | { readonly kind: "git"; @@ -42,6 +40,8 @@ export const readReferenceSourceVcs = async ( }; const resolveSourceHead = async (root: string): Promise => { + // isomorphic-git is loaded on first use so CLI and MCP startup skip it. + const { resolveRef } = await import("isomorphic-git"); const dotgit = join(root, ".git"); if (!(await lstat(dotgit)).isFile()) return resolveRef({ fs, dir: root, ref: "HEAD" }); diff --git a/src/cliBrowserScenarioCommands.ts b/src/cliBrowserScenarioCommands.ts index f98e415cb..a1a1f86e1 100644 --- a/src/cliBrowserScenarioCommands.ts +++ b/src/cliBrowserScenarioCommands.ts @@ -2,7 +2,6 @@ import { Cli } from "incur"; import { z } from "zod"; import { captureBrowserScenario } from "./application/BrowserScenarioCaptureService.js"; -import { createBrowserScenarioProvider } from "./composition/browserScenario.js"; import { CLI_COMMANDS } from "./cliCommandNames.js"; import { parseCliJsonInput, resolveCliJsonPaths } from "./cliJsonInput.js"; import { logCliCommand } from "./cliLogging.js"; @@ -44,6 +43,9 @@ export const registerBrowserScenarioCommands = ( projectInputIssues(scenario.error.issues, input.value), ), ); + // Load Playwright only for this command, not during CLI startup. + const { createBrowserScenarioProvider } = + await import("./composition/browserScenario.js"); const result = await captureBrowserScenario( createBrowserScenarioProvider(environment), scenario.data, diff --git a/tests/boundary/cli/cliStartupImports.test.ts b/tests/boundary/cli/cliStartupImports.test.ts new file mode 100644 index 000000000..c084b6212 --- /dev/null +++ b/tests/boundary/cli/cliStartupImports.test.ts @@ -0,0 +1,76 @@ +import { execFile } from "node:child_process"; +import { mkdir } from "node:fs/promises"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +import { describe, expect, it } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const execute = promisify(execFile); +const MARKER = "REA_TEST_RESOLVED "; +// Dependencies that only one command uses; startup must not resolve them. +const DEFERRED_PACKAGES = ["playwright-core", "isomorphic-git"] as const; +// Report each resolved deferred package on stderr without changing resolution. +const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(` +import { registerHooks } from "node:module"; +const packages = ${JSON.stringify(DEFERRED_PACKAGES)}; +registerHooks({ + resolve(specifier, context, next) { + const resolved = next(specifier, context); + const name = packages.find((item) => + resolved.url.includes("/node_modules/" + item + "/"), + ); + if (name !== undefined) + process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n"); + return resolved; + }, +}); +`)}`; + +const resolvedPackages = async ( + arguments_: readonly string[], +): Promise> => { + const { stderr } = await execute( + process.execPath, + [`--import=${RESOLUTION_HOOK}`, ...arguments_], + { cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 }, + ); + return new Set( + stderr + .split("\n") + .filter((line) => line.startsWith(MARKER)) + .map((line) => line.slice(MARKER.length)), + ); +}; + +const evaluate = (source: string): readonly string[] => [ + "--input-type=module", + "--eval", + source, +]; + +describe("CLI startup imports", () => { + it("detects each deferred package when its command code loads", async () => { + await expect( + resolvedPackages( + evaluate('await import("./dist/composition/browserScenario.js");'), + ), + ).resolves.toContain("playwright-core"); + const source = await createTestTempDirectory("rea-startup-imports-"); + await mkdir(join(source, ".git")); + await expect( + resolvedPackages( + evaluate( + `const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`, + ), + ), + ).resolves.toContain("isomorphic-git"); + }); + + it("does not load command-specific packages to register commands", async () => { + await expect( + resolvedPackages(["scripts/rea.mjs", "--help"]), + ).resolves.toEqual(new Set()); + }); +}); From 33b9b31a6fb50cc3e6f4591d0395dbba15b51f13 Mon Sep 17 00:00:00 2001 From: keemsisi Date: Sat, 10 Oct 2026 06:21:13 +0100 Subject: [PATCH 157/189] perf(javascript): index change-graph nodes once per comparison Resolve each compared graph node through a per-side index while preserving right-hand evidence selection and complete comparison results. Refs #1065. Co-authored-by: keemsisi <7439375+keemsisi@users.noreply.github.com> --- .../javascriptApplicationChangeGraph.test.ts | 107 ++++++++++++++++++ .../javascriptApplicationChangeGraph.ts | 25 ++-- 2 files changed, 124 insertions(+), 8 deletions(-) create mode 100644 src/domain/javascript/javascriptApplicationChangeGraph.test.ts diff --git a/src/domain/javascript/javascriptApplicationChangeGraph.test.ts b/src/domain/javascript/javascriptApplicationChangeGraph.test.ts new file mode 100644 index 000000000..2bbd653af --- /dev/null +++ b/src/domain/javascript/javascriptApplicationChangeGraph.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from "vitest"; + +import { + createJavaScriptApplicationEdge, + createJavaScriptApplicationGraph, + createJavaScriptApplicationNode, + type JavaScriptApplicationGraph, +} from "./javascriptApplicationGraph.js"; +import { + artifactEvidence, + completeCoverage, +} from "./javascriptApplicationGraph.fixture.js"; +import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js"; + +const LEFT_SHA = "a".repeat(64); +const RIGHT_SHA = "b".repeat(64); + +const digest = (value: number): string => value.toString(16).padStart(64, "0"); + +const buildGraph = ( + artifactSha: string, + changed: number, +): JavaScriptApplicationGraph => { + const nodes = ["a", "b", "c", "d"].map((name, index) => + createJavaScriptApplicationNode({ + kind: "javascript-module", + identity: { + strategy: "canonical-path", + stability: "artifact-version", + artifact_sha256: artifactSha, + path: `${name}.js`, + }, + observations: [ + { + label: `${name}.js`, + properties: { + structural_fingerprint_sha256: digest(index + 1), + structural_fingerprint_algorithm: "fixture", + source_sha256: digest(index === 1 || index === 3 ? changed : 0), + }, + evidence: artifactEvidence(artifactSha, `${name}.js`), + }, + ], + }), + ); + const [a, b] = nodes; + if (a === undefined || b === undefined) + throw new Error("Missing fixture node"); + return createJavaScriptApplicationGraph({ + schema: "JavaScriptApplicationGraph", + root_node_ids: [a.node_id], + nodes, + edges: [ + createJavaScriptApplicationEdge({ + source_node_id: a.node_id, + target_node_id: b.node_id, + relation: "imports", + properties: {}, + evidence: artifactEvidence(artifactSha, "a.js"), + }), + ], + coverage: completeCoverage, + limitations: [], + }); +}; + +describe("application change graph", () => { + it("anchors each changed_from edge to its own right-hand observation", () => { + const left = buildGraph(LEFT_SHA, 1); + const right = buildGraph(RIGHT_SHA, 2); + const result = compareJavaScriptApplicationVersions({ + left: { + evidenceId: `ev_${"1".repeat(64)}`, + rootArtifactSha256: LEFT_SHA, + graph: left, + }, + right: { + evidenceId: `ev_${"2".repeat(64)}`, + rootArtifactSha256: RIGHT_SHA, + graph: right, + }, + leftNativeEvidence: [], + rightNativeEvidence: [], + }); + const changedFrom = result.graph.edges.filter( + ({ relation }) => relation === "changed_from", + ); + expect(changedFrom).toHaveLength(2); + for (const edge of changedFrom) { + const source = right.nodes.find( + ({ node_id: id }) => id === edge.source_node_id, + ); + const target = left.nodes.find( + ({ node_id: id }) => id === edge.target_node_id, + ); + expect(source?.observations[0]?.label).toBe( + target?.observations[0]?.label, + ); + expect(edge.evidence.artifact).toEqual( + source?.observations[0]?.evidence.artifact, + ); + expect(edge.evidence.location).toEqual( + source?.observations[0]?.evidence.location, + ); + } + }); +}); diff --git a/src/domain/javascript/javascriptApplicationChangeGraph.ts b/src/domain/javascript/javascriptApplicationChangeGraph.ts index 4c80b3204..134fff520 100644 --- a/src/domain/javascript/javascriptApplicationChangeGraph.ts +++ b/src/domain/javascript/javascriptApplicationChangeGraph.ts @@ -53,8 +53,14 @@ export const buildJavaScriptApplicationChangeGraph = ( ({ source_node_id: source, target_node_id: target }) => retained.has(source) && retained.has(target), ); + const leftById = new Map( + input.left.nodes.map((node) => [node.node_id, node]), + ); + const rightById = new Map( + input.right.nodes.map((node) => [node.node_id, node]), + ); const comparisonEdges = input.items.flatMap((item) => - changedFromEdge(item, input, retained), + changedFromEdge(item, input, retained, leftById, rightById), ); const candidateEdges = uniqueEdges([...sourceEdges, ...comparisonEdges]); const rootNodeIds = preferredRoots.filter((nodeId) => retained.has(nodeId)); @@ -104,6 +110,8 @@ const changedFromEdge = ( item: ApplicationVersionComparisonItem, input: ChangeGraphInput, retained: ReadonlySet, + leftById: ReadonlyMap, + rightById: ReadonlyMap, ): ApplicationEdge[] => { const left = item.left_node_id; const right = item.right_node_id; @@ -117,7 +125,12 @@ const changedFromEdge = ( !retained.has(right) ) return []; - const evidence = comparisonEvidence(item, input); + const evidence = comparisonEvidence( + item, + input, + leftById.get(left), + rightById.get(right), + ); return [ createJavaScriptApplicationEdge({ source_node_id: right, @@ -138,13 +151,9 @@ const changedFromEdge = ( const comparisonEvidence = ( item: ApplicationVersionComparisonItem, input: ChangeGraphInput, + left: ApplicationNode | undefined, + right: ApplicationNode | undefined, ): ApplicationGraphEvidence => { - const right = input.right.nodes.find( - ({ node_id: id }) => id === item.right_node_id, - ); - const left = input.left.nodes.find( - ({ node_id: id }) => id === item.left_node_id, - ); const source = right?.observations[0]?.evidence ?? left?.observations[0]?.evidence; const complete = From 7633dd8d5dcb94eb5c2fca8b69858949c51b0eaf Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:43:01 +0800 Subject: [PATCH 158/189] fix(ghidra): publish Windows verification success after cleanup --- docs/native-investigation.md | 2 +- scripts/verify-packaged-ghidra-windows.mjs | 31 +++++++++++++--------- src/ghidra/GhidraProvider.behavior.test.ts | 26 ++++++++++++++++++ 3 files changed, 46 insertions(+), 13 deletions(-) diff --git a/docs/native-investigation.md b/docs/native-investigation.md index 4dad23b3b..b3051cc64 100644 --- a/docs/native-investigation.md +++ b/docs/native-investigation.md @@ -379,7 +379,7 @@ the tool fails with a `debugger-attach-denied` reason. Install a Ghidra 12.1.x release and the 64-bit full JDK it declares, then configure REA to use them. Ghidra analysis supports Linux x64/arm64 and macOS x64/arm64; each installation requires the matching native decompiler. Experimental Windows x64 P0 admits native -x86-64 PE applications on local NTFS using bundled Job Object ownership, +x86 and x86-64 PE applications and DLLs on local NTFS using bundled Job Object ownership, protected runtime DACLs, and handle-based path admission. See [Windows Ghidra P0](windows-ghidra-p0.md) and [issue #527](https://github.com/morluto/rea/issues/527). On Linux and macOS, `annotate_native_function` atomically edits a function name diff --git a/scripts/verify-packaged-ghidra-windows.mjs b/scripts/verify-packaged-ghidra-windows.mjs index 268d949d9..be21fde12 100644 --- a/scripts/verify-packaged-ghidra-windows.mjs +++ b/scripts/verify-packaged-ghidra-windows.mjs @@ -26,12 +26,21 @@ if (process.platform !== "win32" || process.arch !== "x64") ); const exec = promisify(execFile); const arguments_ = process.argv.slice(2); +const internalWorkspace = arguments_[0] === "--internal-workspace"; +const fixtureArguments = internalWorkspace ? arguments_.slice(2) : arguments_; +const x86Fixture = fixtureArguments.includes("--x86"); +const dllFixture = fixtureArguments.includes("--dll"); +const [packageRootArgument, targetArgument, reportArgument] = + fixtureArguments.filter( + (argument) => argument !== "--x86" && argument !== "--dll", + ); // Windows locks the loaded package-owned addon until the verifier exits. // Keep installation cleanup in a parent that never loads that addon. -if (arguments_[0] !== "--internal-workspace") { +if (!internalWorkspace) { const ownedWorkspace = await mkdtemp(join(tmpdir(), "rea-packaged-ghidra-")); + let result; try { - const result = await exec( + result = await exec( process.execPath, [ fileURLToPath(import.meta.url), @@ -41,8 +50,6 @@ if (arguments_[0] !== "--internal-workspace") { ], { timeout: 900_000, maxBuffer: 8 * 1024 * 1024 }, ); - process.stdout.write(result.stdout); - process.stderr.write(result.stderr); } catch (cause) { if (typeof cause.stdout === "string") process.stdout.write(cause.stdout); if (typeof cause.stderr === "string") process.stderr.write(cause.stderr); @@ -50,17 +57,17 @@ if (arguments_[0] !== "--internal-workspace") { } finally { await rm(ownedWorkspace, { recursive: true, force: true }); } + const report = JSON.parse(result.stdout); + report.workspaceCleanup = true; + report.ok = true; + if (reportArgument !== undefined) + await writeFile(reportArgument, `${JSON.stringify(report)}\n`); + process.stdout.write(`${JSON.stringify(report)}\n`); + process.stderr.write(result.stderr); process.exit(0); } assert.ok(arguments_[1] !== undefined, "Missing verifier workspace."); const workspace = resolve(arguments_[1]); -const fixtureArguments = arguments_.slice(2); -const x86Fixture = fixtureArguments.includes("--x86"); -const dllFixture = fixtureArguments.includes("--dll"); -const [packageRootArgument, targetArgument, reportArgument] = - fixtureArguments.filter( - (argument) => argument !== "--x86" && argument !== "--dll", - ); let packageRoot = resolve(packageRootArgument ?? "."); // The default lane verifies the npm artifact in an isolated prefix. Explicit // package roots support an already-installed artifact without a second install. @@ -402,7 +409,7 @@ try { assert.deepEqual(await readdir(join(callerDirectory, name)), []); report.callerScriptCollisionsPreserved = true; report.runtimeCleanup = true; - report.ok = true; + // Only the parent can attest success after removing the installation. if (reportArgument !== undefined) await writeFile(reportArgument, `${JSON.stringify(report)}\n`); process.stdout.write(`${JSON.stringify(report)}\n`); diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index 88e1eb07f..c607b9950 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -198,6 +198,32 @@ describe("Ghidra Mach-O slice support", () => { }); describe("Ghidra platform support", () => { + it("commits the PE role and managed classification to profile identity", async () => { + const ghidra = provider({ ...installationHost(), platform: "win32" }); + const application = peTarget("x86_64"); + const library = { + ...application, + executableRole: "shared-library", + } as const; + const digests = new Set(); + for (const target of [ + application, + library, + { ...library, managed: true }, + ]) { + const resolved = await ghidra.resolveAnalysisProfile(target); + if (!resolved.ok) throw resolved.error; + const profile = resolved.value.profile; + if (profile === null) throw new Error("Expected a PE analysis profile"); + expect(profile.parameters).toMatchObject({ + executable_role: target.executableRole, + managed: target.managed, + }); + digests.add(profile.digest); + } + expect(digests.size).toBe(3); + }); + it("keeps Windows annotation mutation unavailable independently of native controls", () => { const ghidra = provider({ ...installationHost(), platform: "win32" }); expect( From ea1dbda1c747400fe2228c1802a3721995216277 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:47:06 +0800 Subject: [PATCH 159/189] test(ghidra): share result projection client setup --- src/ghidra/GhidraProvider.behavior.test.ts | 74 ++++++++-------------- 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index c607b9950..c0518297b 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -540,24 +540,23 @@ describe("Ghidra client projection", () => { }); describe("Ghidra result projection", () => { + const createElfClient = async (ghidra: GhidraProvider) => { + const target = executableTarget("elf", "x86_64"); + const resolved = await ghidra.resolveAnalysisProfile(target); + if (!resolved.ok) throw resolved.error; + if (resolved.value.profile === null) + throw new Error("Expected a bound Ghidra profile"); + return ghidra.createClient(target, resolved.value.profile); + }; + it("rejects malformed inventory output before Evidence creation", async () => { const ghidra = provider(installationHost(), () => ({ start: () => Promise.resolve(ok(sessionInfo())), callTool: () => Promise.resolve(ok({ items: "not-an-inventory" })), close: () => Promise.resolve(ok(null)), })); - const resolved = await ghidra.resolveAnalysisProfile( - executableTarget("elf", "x86_64"), - ); - if (!resolved.ok) throw resolved.error; - if (resolved.value.profile === null) - throw new Error("Expected a bound Ghidra profile"); - - await expect( - ghidra - .createClient(executableTarget("elf", "x86_64"), resolved.value.profile) - .execute("list_procedures", {}), - ).resolves.toMatchObject({ + const client = await createElfClient(ghidra); + await expect(client.execute("list_procedures", {})).resolves.toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" }, }); @@ -586,21 +585,13 @@ describe("Ghidra result projection", () => { ), close: () => Promise.resolve(ok(null)), })); - const resolved = await ghidra.resolveAnalysisProfile( - executableTarget("elf", "x86_64"), - ); - if (!resolved.ok) throw resolved.error; - if (resolved.value.profile === null) - throw new Error("Expected a bound Ghidra profile"); - + const client = await createElfClient(ghidra); await expect( - ghidra - .createClient( - executableTarget("elf", "x86_64"), - resolved.value.profile, - ) - .execute("list_procedures", {}), - ).resolves.toMatchObject({ ok: false, error: { _tag: tag } }); + client.execute("list_procedures", {}), + ).resolves.toMatchObject({ + ok: false, + error: { _tag: tag }, + }); }, ); @@ -622,19 +613,12 @@ describe("Ghidra result projection", () => { ), close: () => Promise.resolve(ok(null)), })); - const resolved = await ghidra.resolveAnalysisProfile( - executableTarget("elf", "x86_64"), - ); - if (!resolved.ok) throw resolved.error; - if (resolved.value.profile === null) - throw new Error("Expected a bound profile"); + const client = await createElfClient(ghidra); await expect( - ghidra - .createClient(executableTarget("elf", "x86_64"), resolved.value.profile) - .execute("annotate_native_function", { - procedure: "0x10100", - name: "bad name", - }), + client.execute("annotate_native_function", { + procedure: "0x10100", + name: "bad name", + }), ).resolves.toMatchObject({ ok: false, error: { @@ -662,16 +646,10 @@ describe("Ghidra result projection", () => { ), close: () => Promise.resolve(ok(null)), })); - const resolved = await ghidra.resolveAnalysisProfile( - executableTarget("elf", "x86_64"), - ); - if (!resolved.ok) throw resolved.error; - if (resolved.value.profile === null) - throw new Error("Expected a bound Ghidra profile"); - - const result = await ghidra - .createClient(executableTarget("elf", "x86_64"), resolved.value.profile) - .execute("procedure_pseudo_code", { procedure: "main" }); + const client = await createElfClient(ghidra); + const result = await client.execute("procedure_pseudo_code", { + procedure: "main", + }); expect(result).toMatchObject({ ok: false, error: { _tag: tag }, From e09cfe9b5970d75da478c9dd741451cc2be5c91a Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:47:15 +0800 Subject: [PATCH 160/189] fix(javascript): invalidate references stored through property targets (#1445) * fix(javascript): invalidate references stored through property targets * refactor(javascript): share rest keys and return-shape fixtures --- docs/javascript-application-workflows.md | 6 +- src/domain/javascript/javascriptAstValues.ts | 10 ++ .../javascript/javascriptSemanticAnalysis.ts | 14 +-- .../javascriptSemanticIterationSources.ts | 69 ++++++++++--- .../javascriptIterationAliases.test.ts | 81 ++------------- .../applications/javascriptSlotStores.test.ts | 98 +++++++++++++++++++ tests/fixtures/javascriptReturnShapes.ts | 91 +++++++++++++++++ 7 files changed, 271 insertions(+), 98 deletions(-) create mode 100644 tests/acceptance/applications/javascriptSlotStores.test.ts create mode 100644 tests/fixtures/javascriptReturnShapes.ts diff --git a/docs/javascript-application-workflows.md b/docs/javascript-application-workflows.md index f26c16d1f..bdc0dcf21 100644 --- a/docs/javascript-application-workflows.md +++ b/docs/javascript-application-workflows.md @@ -183,8 +183,10 @@ Direct return expressions, including expression-bodied arrows, are evaluated through an execution-free value lattice. Literal object fields and direct return sites are represented in the result. Calls, dynamic spreads, computed keys, and parser recovery remain partial or unknown. -Objects and arrays passed to calls, constructors, or tagged templates, or used -as method receivers, are not assumed unchanged after the invocation. Aliases +Objects and arrays passed to calls, constructors, or tagged templates, used +as method receivers, or stored through property targets are not assumed +unchanged afterward. Property stores conservatively retain reference escape +uncertainty rather than pretending to execute later writes. Aliases and shared children in spread and rest copies retain that uncertainty; copied primitive slots and unrelated containing properties remain known. Object rest excludes consumed keys, array rest excludes the consumed prefix for known diff --git a/src/domain/javascript/javascriptAstValues.ts b/src/domain/javascript/javascriptAstValues.ts index f0a0528c0..5479c8d1f 100644 --- a/src/domain/javascript/javascriptAstValues.ts +++ b/src/domain/javascript/javascriptAstValues.ts @@ -76,6 +76,16 @@ export const semanticStaticPropertyKey = ( return !computed && t.isIdentifier(property) ? property.name : null; }; +/** Read exact consumed object-pattern keys, leaving dynamic keys unknown. */ +export const semanticObjectPatternKeys = ( + pattern: t.ObjectPattern, +): readonly string[] => + pattern.properties.flatMap((property) => { + if (t.isRestElement(property)) return []; + const key = semanticStaticPropertyKey(property.key, property.computed); + return key === null ? [] : [key]; + }); + /** * Display an exact JavaScript string as nonempty label text. Graph labels and * artifact-local keys are nonempty, so the legal empty value is shown as `""`; diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 1cf53fb31..452d29074 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -14,7 +14,10 @@ import { immutableSemanticBindings, immutableSemanticScopes, } from "./javascriptSemanticProjection.js"; -import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; +import { + semanticObjectPatternKeys, + semanticStaticPropertyKey, +} from "./javascriptAstValues.js"; import type { JavaScriptSemanticAnalysisState, JavaScriptSemanticBindingState, @@ -880,14 +883,7 @@ const bindPattern = (input: BindPatternInput): void => { referenceOnly: true, copyKind: "object-rest", copyProjectionOffset: projection.length, - copyExcludedKeys: pattern.properties.flatMap((property) => { - if (t.isRestElement(property)) return []; - const key = semanticStaticPropertyKey( - property.key, - property.computed, - ); - return key === null ? [] : [key]; - }), + copyExcludedKeys: semanticObjectPatternKeys(pattern), }); } else { const name = semanticStaticPropertyKey(property.key, property.computed); diff --git a/src/domain/javascript/javascriptSemanticIterationSources.ts b/src/domain/javascript/javascriptSemanticIterationSources.ts index c83eb94ad..ea3708e51 100644 --- a/src/domain/javascript/javascriptSemanticIterationSources.ts +++ b/src/domain/javascript/javascriptSemanticIterationSources.ts @@ -1,14 +1,21 @@ import * as t from "@babel/types"; -import { semanticStaticPropertyKey } from "./javascriptAstValues.js"; -import { semanticArrayIndex } from "./javascriptSemanticPropertyPaths.js"; +import { + semanticObjectPatternKeys, + semanticStaticPropertyKey, +} from "./javascriptAstValues.js"; +import { + semanticArrayIndex, + type JavaScriptSemanticPropertyPath, +} from "./javascriptSemanticPropertyPaths.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; interface IterationSourceValue { readonly node: t.Node; - readonly projection: readonly (string | number | null)[]; + readonly projection: JavaScriptSemanticPropertyPath; } -/** An iterator receiver or yielded reference store, with default guards. */ +/** An iterator receiver or property reference store, with default guards. */ export interface SemanticIterationSource extends IterationSourceValue { readonly kind: "iteration" | "reference-store"; readonly mutation: t.Node; @@ -69,11 +76,25 @@ const visit = ( guards: SourceGuards = {}, ): void => { const { sources, mutation } = context; - if (t.isForOfStatement(mutation) && t.isMemberExpression(pattern)) { - // Storing a yielded reference in a property has no lexical loop binding. - // Preserve its escape rather than assuming later writes cannot reach it. + if (t.isMemberExpression(pattern)) { + // Property stores have no lexical alias binding. Preserve the selected + // reference's escape rather than claiming later writes cannot reach it. if (source !== undefined) - add(sources, source, mutation, guards, "reference-store"); + add( + sources, + source.restStartIndex === undefined + ? source + : { + node: source.node, + projection: [ + ...source.projection, + { excludedKeys: [], startIndex: source.restStartIndex }, + ], + }, + mutation, + guards, + "reference-store", + ); return; } if (t.isTSParameterProperty(pattern)) { @@ -104,8 +125,29 @@ const visit = ( } if (t.isObjectPattern(pattern)) { for (const property of pattern.properties) { - // Object rest creates a fresh object and has no iterable binding pattern. - if (t.isRestElement(property)) continue; + if (t.isRestElement(property)) { + // A rest copy owns its scalar slots; only selected child references + // escape when that fresh copy is stored through a member target. + visit( + context, + property.argument, + source === undefined + ? undefined + : { + node: source.node, + projection: [ + ...source.projection, + { + excludedKeys: [ + ...new Set(semanticObjectPatternKeys(pattern)), + ].sort(compareUnicodeCodePoints), + }, + ], + }, + guards, + ); + continue; + } visit( context, property.value, @@ -144,7 +186,7 @@ const visit = ( visit(context, pattern.argument, undefined, guards); }; -/** Describe implicit iteration sources without deciding their runtime values. */ +/** Describe iterator receivers and property reference stores without evaluation. */ export const semanticIterationSources = ( node: t.Node, parent: t.Node | null, @@ -153,7 +195,10 @@ export const semanticIterationSources = ( const context = { sources, mutation: node }; if (t.isVariableDeclarator(node) && node.init != null) visit(context, node.id, { node: node.init, projection: [] }); - else if (t.isAssignmentExpression(node) && node.operator === "=") + else if ( + t.isAssignmentExpression(node) && + ["=", "||=", "&&=", "??="].includes(node.operator) + ) visit(context, node.left, { node: node.right, projection: [] }); else if (t.isForOfStatement(node)) { add(sources, { node: node.right, projection: [] }, node, {}); diff --git a/tests/acceptance/applications/javascriptIterationAliases.test.ts b/tests/acceptance/applications/javascriptIterationAliases.test.ts index 103995480..a7f039eb8 100644 --- a/tests/acceptance/applications/javascriptIterationAliases.test.ts +++ b/tests/acceptance/applications/javascriptIterationAliases.test.ts @@ -1,13 +1,9 @@ -import { Client } from "@modelcontextprotocol/client"; -import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; -import { 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 { projectedExportReturnShapesSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js"; -import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + verifyJavaScriptReturnShapes, + type JavaScriptReturnFields, +} from "../../fixtures/javascriptReturnShapes.js"; import { cliTest } from "../../support/cli/cliFixture.js"; const source = [ @@ -37,27 +33,7 @@ const source = [ "export function shadowed() { const t = { x: 1 }; const shared = { x: 3 }; for (const t of [shared]) t.x = 2; return t.x; }", ].join("\n"); -const assertReturns = (value: unknown): void => { - const analysis = javascriptApplicationAnalysisResultSchema.parse(value); - const projections = analysis.graph.nodes - .flatMap(({ observations }) => observations) - .filter( - ({ properties }) => properties.semantic_role === "export-return-shapes", - ) - .map(({ properties }) => - projectedExportReturnShapesSchema.parse(properties), - ); - const fields = (name: string) => { - const projection = projections.find( - ({ exported_name }) => exported_name === name, - ); - if (projection === undefined) throw new Error(`Missing export ${name}`); - expect(projection.return_shape_coverage).toMatchObject({ - status: "complete", - projection_complete: true, - }); - return projection.static_return_shapes.flatMap(({ fields }) => fields); - }; +const assertReturns = (fields: JavaScriptReturnFields): void => { expect(fields("inline")).toEqual( expect.arrayContaining([ expect.objectContaining({ path: "/x", state: "unknown" }), @@ -95,51 +71,6 @@ const assertReturns = (value: unknown): void => { cliTest( "preserves yielded-object mutation uncertainty through CLI and stdio MCP", - async ({ cli }) => { - const root = await createTestTempDirectory("rea-iteration-aliases-"); - await writeFile(join(root, "app.js"), source); - const cliResponse = await cli.run({ - arguments: [ - "analyze-javascript-application", - root, - "--artifact-format", - "directory", - "--json", - ], - }); - expect(cliResponse.exitCode).toBe(0); - const contract = toolContract("analyze_javascript_application"); - const cliEvidence = contract.outputSchema.parse(cliResponse.json); - assertReturns(cliEvidence.normalized_result); - const client = new Client({ name: "iteration-aliases-e2e", 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 response = await client.callTool({ - name: "analyze_javascript_application", - arguments: { input_path: root, format: "directory" }, - }); - expect(response.isError).not.toBe(true); - const evidence = contract.outputSchema.parse(response.structuredContent); - expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); - assertReturns(evidence.normalized_result); - const text = response.content.find((item) => item.type === "text"); - if (text?.type !== "text") throw new Error("Missing MCP text result"); - assertReturns( - contract.outputSchema.parse(JSON.parse(text.text)).normalized_result, - ); - await client.ping(); - } finally { - await client.close(); - await transport.close(); - } - }, + ({ cli }) => verifyJavaScriptReturnShapes(cli, source, assertReturns), 120_000, ); diff --git a/tests/acceptance/applications/javascriptSlotStores.test.ts b/tests/acceptance/applications/javascriptSlotStores.test.ts new file mode 100644 index 000000000..3af7e3eee --- /dev/null +++ b/tests/acceptance/applications/javascriptSlotStores.test.ts @@ -0,0 +1,98 @@ +import { expect } from "vitest"; + +import { + verifyJavaScriptReturnShapes, + type JavaScriptReturnFields, +} from "../../fixtures/javascriptReturnShapes.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +const stores = { + object: "const o = {a: {x: 0}}; o.a = shared; o.a.x = 2;", + array: "const arr = [{x: 0}]; arr[0] = shared; arr[0].x = 2;", + captured: "const o = {a: {x: 0}}; o.a = shared; const t = o.a; t.x = 2;", + nested: "const o = {a: {b: {x: 0}}}; o.a.b = shared; o.a.b.x = 2;", + quoted: 'const o = {}; o["a/b~c"] = shared; o["a/b~c"].x = 2;', + dynamic: 'const o = {}; const key = "entry"; o[key] = shared; o[key].x = 2;', + receiverAlias: "const o = {}; const t = o; t.a = shared; o.a.x = 2;", + transitive: "const p = {}; const o = {}; o.a = p; p.b = shared; o.a.b.x = 2;", + overwritten: "const o = {}; o.a = {x: 0}; o.a = shared; o.a.x = 2;", + replacedReference: + "const o = {}; const other = {x: 0}; o.a = other; o.a = shared; o.a.x = 2;", + copiedDestination: + "const o = {}; o.a = shared; const copy = {...o}; copy.a.x = 2;", + iteration: "const arr = []; arr[0] = shared; for (const t of arr) t.x = 2;", + nestedArray: "const o = {}; o.a = [shared]; o.a[0].x = 2;", + orAssignment: "const o = {a: null}; o.a ||= shared; o.a.x = 2;", + nullishAssignment: "const o = {a: null}; o.a ??= shared; o.a.x = 2;", + andAssignment: "const o = {a: {x: 0}}; o.a &&= shared; o.a.x = 2;", + objectPattern: "const o = {}; ({child: o.a} = {child: shared}); o.a.x = 2;", + arrayPattern: "const o = {}; [o.a] = [shared]; o.a.x = 2;", + defaultPattern: "const o = {}; ({child: o.a = shared} = {}); o.a.x = 2;", + objectRestMember: + "const o = {}; ({...o.a} = {child: shared}); o.a.child.x = 2;", + arrayRestMember: "const o = {}; [...o.a] = [shared]; o.a[0].x = 2;", + iteratedObjectRest: + "const o = {}; for ({...o.a} of [{child: shared}]) o.a.child.x = 2;", + iteratedArrayRest: "const o = {}; for ([...o.a] of [[shared]]) o.a[0].x = 2;", + classField: + "class Holder {} const o = new Holder(); o.a = shared; o.a.x = 2;", +}; +const source = [ + ...Object.entries(stores).map( + ([name, body]) => + `export function ${name}() { const shared = {x: 1}; ${body} return shared.x; }`, + ), + "export function primitive() { const n = 1; const o = {}; o.a = n; o.a = 2; return n; }", + "export function nestedChild() { const shared = {inner: {x: 1}}; const o = {}; o.a = shared; o.a.inner.x = 2; return shared.inner.x; }", + "export function readOnlyStore() { const shared = {x: 1}; const o = {}; o.a = shared; const captured = o.a.x; return shared.x; }", + "export function copiedScalar() { const shared = {x: 1}; const o = {}; o.a = {...shared}; o.a.x = 2; return shared.x; }", + "export function copiedArrayScalar() { const shared = {x: 1}; const o = {}; o.a = [shared.x]; o.a[0] = 2; return shared.x; }", + "export function unrelated() { const shared = {x: 1}; const other = {x: 9}; const o = {}; o.a = shared; o.a.x = 2; return other.x; }", + "export function copiedChild() { const child = {x: 1}; const parent = {child, keep: 7}; const o = {}; o.a = {...parent}; o.a.child.x = 2; return {child: child.x, keep: parent.keep}; }", + "export function objectRestExclusion() { const child = {x: 1}; const skip = {x: 3}; const parent = {child, skip, keep: 7}; const o = {}; let ignored; ({skip: ignored, ...o.a} = parent); o.a.child.x = 2; return {child: child.x, skip: skip.x, keep: parent.keep}; }", + "export function arrayRestOffset() { const child = {x: 1}; const skip = {x: 3}; const items = [skip, child]; const o = {}; let ignored; [ignored, ...o.a] = items; o.a[0].x = 2; return {child: child.x, skip: items[0].x}; }", +].join("\n"); + +const assertReturns = (fields: JavaScriptReturnFields): void => { + for (const name of [...Object.keys(stores), "nestedChild"]) { + const field = fields(name).find(({ path }) => path === ""); + expect(field, name).toBeDefined(); + expect(field?.state, name).toMatch(/^(unknown|literal)$/); + if (field?.state === "literal") expect(field.value, name).toBe(2); + } + const readOnly = fields("readOnlyStore").find(({ path }) => path === ""); + expect(readOnly?.state).toMatch(/^(unknown|literal)$/); + if (readOnly?.state === "literal") expect(readOnly.value).toBe(1); + for (const [name, value] of Object.entries({ + primitive: 1, + copiedScalar: 1, + copiedArrayScalar: 1, + unrelated: 9, + })) + expect(fields(name), name).toContainEqual( + expect.objectContaining({ path: "", state: "literal", value }), + ); + const child = fields("copiedChild").find(({ path }) => path === "/child"); + expect(child?.state).toMatch(/^(unknown|literal)$/); + if (child?.state === "literal") expect(child.value).toBe(2); + expect(fields("copiedChild")).toContainEqual( + expect.objectContaining({ path: "/keep", state: "literal", value: 7 }), + ); + for (const name of ["objectRestExclusion", "arrayRestOffset"]) { + const child = fields(name).find(({ path }) => path === "/child"); + expect(child?.state, name).toMatch(/^(unknown|literal)$/); + if (child?.state === "literal") expect(child.value, name).toBe(2); + expect(fields(name), name).toContainEqual( + expect.objectContaining({ path: "/skip", state: "literal", value: 3 }), + ); + } + expect(fields("objectRestExclusion")).toContainEqual( + expect.objectContaining({ path: "/keep", state: "literal", value: 7 }), + ); +}; + +cliTest( + "does not report stale literals after storing references in member slots", + ({ cli }) => verifyJavaScriptReturnShapes(cli, source, assertReturns), + 120_000, +); diff --git a/tests/fixtures/javascriptReturnShapes.ts b/tests/fixtures/javascriptReturnShapes.ts new file mode 100644 index 000000000..02c66bc84 --- /dev/null +++ b/tests/fixtures/javascriptReturnShapes.ts @@ -0,0 +1,91 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { 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 { projectedExportReturnShapesSchema } from "../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js"; +import { createTestTempDirectory } from "./temporaryDirectory.js"; +import type { TestCli } from "../support/cli/cliFixture.js"; + +const exportedReturnFields = (value: unknown) => { + const analysis = javascriptApplicationAnalysisResultSchema.parse(value); + const projections = analysis.graph.nodes + .flatMap(({ observations }) => observations) + .filter( + ({ properties }) => properties.semantic_role === "export-return-shapes", + ) + .map(({ properties }) => + projectedExportReturnShapesSchema.parse(properties), + ); + return (name: string) => { + const projection = projections.find( + ({ exported_name }) => exported_name === name, + ); + if (projection === undefined) throw new Error(`Missing export ${name}`); + expect(projection.return_shape_coverage).toMatchObject({ + status: "complete", + projection_complete: true, + }); + return projection.static_return_shapes.flatMap(({ fields }) => fields); + }; +}; + +/** Select complete return fields from a real JavaScript application result. */ +export type JavaScriptReturnFields = ReturnType; + +/** Exercise identical return assertions through the compiled CLI and stdio MCP. */ +export const verifyJavaScriptReturnShapes = async ( + cli: TestCli, + source: string, + check: (fields: JavaScriptReturnFields) => void, +): Promise => { + const root = await createTestTempDirectory("rea-return-shapes-"); + await writeFile(join(root, "app.js"), source); + const cliResponse = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + }); + expect(cliResponse.exitCode).toBe(0); + const contract = toolContract("analyze_javascript_application"); + const cliEvidence = contract.outputSchema.parse(cliResponse.json); + check(exportedReturnFields(cliEvidence.normalized_result)); + const client = new Client({ name: "return-shapes-e2e", 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 response = await client.callTool({ + name: "analyze_javascript_application", + arguments: { input_path: root, format: "directory" }, + }); + expect(response.isError).not.toBe(true); + const evidence = contract.outputSchema.parse(response.structuredContent); + expect(evidence.evidence_id).toBe(cliEvidence.evidence_id); + check(exportedReturnFields(evidence.normalized_result)); + const text = response.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + check( + exportedReturnFields( + contract.outputSchema.parse(JSON.parse(text.text)).normalized_result, + ), + ); + await client.ping(); + } finally { + await client.close(); + await transport.close(); + } +}; From 0d2082d36b8bed3cda5daa22adee2163652fc511 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:56:40 +0800 Subject: [PATCH 161/189] fix(javascript): recognize unchanged var and let Electron aliases --- .../javascript/javascriptSemanticAnalysis.ts | 14 ++++- .../electronApplicationAnalysis.test.ts | 56 +++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index b5c1c7f5d..d490adf65 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -352,9 +352,17 @@ const bindingOrigin = ( ? binding.directOrigins[0] : undefined; const [initializer] = binding.initializers; - if (binding.mutable || binding.initializers.length !== 1) return undefined; - const origin = semanticRequireOrigin(initializer?.node, state); - const projection = initializer?.projection ?? []; + // A var/let declaration permits writes without proving one occurred. + // Require one unconditional initializer and no actual binding writes. + if ( + initializer === undefined || + binding.initializers.length !== 1 || + binding.definitions.some(({ kind }) => kind === "assignment") || + state.conditionalInitializers.has(initializer.node) + ) + return undefined; + const origin = semanticRequireOrigin(initializer.node, state); + const projection = initializer.projection; return origin === undefined || !projection.every((key): key is string => typeof key === "string") ? undefined diff --git a/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts b/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts index 4180e1818..dd7bd8809 100644 --- a/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts +++ b/tests/composition/javascript-applications/electronApplicationAnalysis.test.ts @@ -116,6 +116,18 @@ describe("static Electron application analysis", () => { expect(handledChannels.sort()).toEqual(["rea:read", "rea:write"]); }); + it("maps unchanged var and let require aliases while excluding reassigned bindings", async () => { + const root = await requireAliasFixtureDirectory(); + + const result = await reconstructJavaScriptArtifact({ input_path: root }); + + expect(result.electron_summary.ipc).toMatchObject({ + main_handlers: 2, + paired_renderer_transmissions: 2, + unpaired_literal_renderer_transmissions: 0, + }); + }); + it("returns a tagged cancellation without executing application code", async () => { const root = await fixtureDirectory(); const controller = new AbortController(); @@ -326,6 +338,50 @@ const fixtureDirectory = async (): Promise => { return root; }; +const requireAliasFixtureDirectory = async (): Promise => { + const root = await createTestTempDirectory("rea-electron-require-aliases-"); + await Promise.all([ + writeFile( + join(root, "package.json"), + JSON.stringify({ + name: "rea-electron-require-aliases", + main: "main.cjs", + }), + ), + writeFile( + join(root, "main.cjs"), + String.raw` +var { ipcMain: main } = require("electron"); +let listener = require("electron/main").ipcMain; +main.handle("rea:read", async () => "value"); +listener.on("rea:write", () => undefined); + +let replaced = require("electron").ipcMain; +replaced = { handle() {} }; +replaced.handle("rea:reassigned", () => undefined); + +var assignedLater; +assignedLater.handle("rea:before-assignment", () => undefined); +assignedLater = require("electron").ipcMain; + +if (globalThis.registerIpc) { + var conditional = require("electron").ipcMain; +} +conditional.handle("rea:conditional", () => undefined); +`, + ), + writeFile( + join(root, "preload.cjs"), + String.raw` +const { ipcRenderer } = require("electron"); +ipcRenderer.invoke("rea:read"); +ipcRenderer.send("rea:write", "value"); +`, + ), + ]); + return root; +}; + const renamedBindingFixtureDirectory = async (): Promise => { const root = await createTestTempDirectory("rea-electron-renamed-"); await Promise.all([ From 66863b609fe5bdbb46b8634399ea08439a94a9f4 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:02:02 +0800 Subject: [PATCH 162/189] test(javascript): reuse comparison node fixtures Use the established typed graph fixture constructor while retaining right-hand comparison provenance assertions. Restore the unchanged duplicate-code gate on combined main. Closes #1446. Refs #1434, #1443, #1065. --- .../javascriptApplicationChangeGraph.test.ts | 28 ++++++++----------- .../javascriptApplicationGraph.fixture.ts | 2 +- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/domain/javascript/javascriptApplicationChangeGraph.test.ts b/src/domain/javascript/javascriptApplicationChangeGraph.test.ts index 2bbd653af..e3c8e1310 100644 --- a/src/domain/javascript/javascriptApplicationChangeGraph.test.ts +++ b/src/domain/javascript/javascriptApplicationChangeGraph.test.ts @@ -3,12 +3,12 @@ import { describe, expect, it } from "vitest"; import { createJavaScriptApplicationEdge, createJavaScriptApplicationGraph, - createJavaScriptApplicationNode, type JavaScriptApplicationGraph, } from "./javascriptApplicationGraph.js"; import { artifactEvidence, completeCoverage, + fixtureNode, } from "./javascriptApplicationGraph.fixture.js"; import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js"; @@ -22,26 +22,22 @@ const buildGraph = ( changed: number, ): JavaScriptApplicationGraph => { const nodes = ["a", "b", "c", "d"].map((name, index) => - createJavaScriptApplicationNode({ - kind: "javascript-module", - identity: { + fixtureNode( + "javascript-module", + { strategy: "canonical-path", stability: "artifact-version", artifact_sha256: artifactSha, path: `${name}.js`, }, - observations: [ - { - label: `${name}.js`, - properties: { - structural_fingerprint_sha256: digest(index + 1), - structural_fingerprint_algorithm: "fixture", - source_sha256: digest(index === 1 || index === 3 ? changed : 0), - }, - evidence: artifactEvidence(artifactSha, `${name}.js`), - }, - ], - }), + `${name}.js`, + { + structural_fingerprint_sha256: digest(index + 1), + structural_fingerprint_algorithm: "fixture", + source_sha256: digest(index === 1 || index === 3 ? changed : 0), + }, + artifactEvidence(artifactSha, `${name}.js`), + ), ); const [a, b] = nodes; if (a === undefined || b === undefined) diff --git a/src/domain/javascript/javascriptApplicationGraph.fixture.ts b/src/domain/javascript/javascriptApplicationGraph.fixture.ts index 00f7c229a..3002b822f 100644 --- a/src/domain/javascript/javascriptApplicationGraph.fixture.ts +++ b/src/domain/javascript/javascriptApplicationGraph.fixture.ts @@ -109,7 +109,7 @@ type FixtureNodeArguments = [ evidence: ApplicationGraphEvidence, ]; -const fixtureNode = ( +export const fixtureNode = ( ...[kind, identity, label, properties, evidence]: FixtureNodeArguments ): FixtureNode => createJavaScriptApplicationNode({ From 1ec490f36180cf6d3a8f353e9e43920dbd81ece0 Mon Sep 17 00:00:00 2001 From: Zeynel <137368801+zeynelacikgoez@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:04:31 +0200 Subject: [PATCH 163/189] fix(javascript): stop replaying earlier writes for each object property write Repeated property writes to one object made member-mutation collection cubic. Each write evaluated its target binding to rule out a primitive, and every evaluation folded all earlier mutation paths, copying every slot once per path. 2,000 writes to one object took 27 s and 4,000 took 203 s. - A recorded write always leaves a non-primitive binding value, so only the first write to a binding needs the primitive check. - Apply mutation paths per slot in one pass with the same ordering semantics instead of one full slot copy per path. Co-authored-by: Claude Opus 5.5 Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> --- ...tSemanticAnalysis.member_mutations.test.ts | 21 ++++ .../javascriptSemanticMemberMutations.ts | 5 +- .../javascriptSemanticMutationValues.ts | 118 ++++++++++++------ .../javascript/javascriptSemanticValues.ts | 10 +- 4 files changed, 106 insertions(+), 48 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts index f28436eb1..3450060cb 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts @@ -590,3 +590,24 @@ describe("property mutations through TypeScript satisfies aliases", () => { ).toEqual({ status: "literal", value: "TOKEN" }); }); }); + +describe("property mutation collection on minified bundles", () => { + it("records each write to one object without replaying earlier writes", () => { + const writes = Array.from( + { length: 2000 }, + (_, index) => `source.p${index} = ${index};`, + ).join(" "); + const start = performance.now(); + const value = resultValue( + `const source = { token: "TOKEN" }; ${writes} return [source.token, source.p1999];`, + ); + expect(performance.now() - start).toBeLessThan(2000); + expect(value).toMatchObject({ + status: "array", + items: [ + { value: { status: "literal", value: "TOKEN" } }, + { value: { status: "unknown" } }, + ], + }); + }, 30000); +}); diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 4e4ea7b8b..1414d407f 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -194,8 +194,11 @@ export const collectSemanticMemberMutations = ( current.originAt?.end, ]); if (recordedEffects.has(identity)) continue; + // A recorded write invalidates the binding to a non-primitive value, so + // only its first write can target a primitive. Re-evaluating it would + // replay every earlier write and make repeated writes superlinear. const value = - effect === "write" + effect === "write" && binding.mutatedPaths.length === 0 ? evaluateSemanticBinding(binding, state) : undefined; const primitiveWrite = diff --git a/src/domain/javascript/javascriptSemanticMutationValues.ts b/src/domain/javascript/javascriptSemanticMutationValues.ts index dbbc9d457..bc2213da7 100644 --- a/src/domain/javascript/javascriptSemanticMutationValues.ts +++ b/src/domain/javascript/javascriptSemanticMutationValues.ts @@ -33,49 +33,89 @@ export const invalidateSemanticEscapedPath = ( : { ...value, items: value.items.map(invalidateChild) }; }; -/** Invalidate only slots that an explicit mutation can affect. */ -export const invalidateSemanticMutationPath = ( +/** + * Invalidate only slots that explicit mutations can affect, as if applying each + * path in order. Paths are grouped per slot so that many writes to one object + * cost one pass over its slots rather than one pass per write. + */ +export const invalidateSemanticMutationPaths = ( value: JavaScriptSemanticValue, - path: JavaScriptSemanticPropertyPath, + paths: readonly JavaScriptSemanticPropertyPath[], ): JavaScriptSemanticValue => { - const [key, ...remaining] = path; - const unknown: JavaScriptSemanticValue = { - status: "unknown", - reason: "This property may have been mutated.", + if (paths.length === 0) return value; + // An unknown key or a replaced value leaves nothing that a later path can + // restore, wherever it occurs in the sequence. + if ( + (value.status !== "object" && value.status !== "array") || + paths.some(([key]) => key === undefined || key === null) + ) + return { + status: "unknown", + reason: "This property may have been mutated.", + }; + // Writing an array length discards every item known before it. + const reset = + value.status === "array" + ? paths.findLastIndex(([key]) => key === "length") + : -1; + const base: typeof value = + reset < 0 + ? value + : { status: "array", items: [], unknownItems: true, omittedItems: null }; + const slots = base.status === "object" ? base.properties : base.items; + const slotsByName = new Map(); + slots.forEach((property, index) => { + const indexes = slotsByName.get(property.name) ?? []; + indexes.push(index); + slotsByName.set(property.name, indexes); + }); + const slotPaths = new Map(); + const replacedSlots = new Set(); + const select = (index: number, remaining: JavaScriptSemanticPropertyPath) => { + const selected = slotPaths.get(index) ?? []; + selected.push(remaining); + slotPaths.set(index, selected); + if (remaining.length === 0) replacedSlots.add(index); }; - if (key === undefined || key === null) return unknown; - if (value.status === "object" || value.status === "array") { - if (value.status === "array" && key === "length") - return { - status: "array", - items: [], - unknownItems: true, - omittedItems: null, - }; - const slots = value.status === "object" ? value.properties : value.items; - const observed = slots.some((property) => - semanticPropertyPathKeyMatches(key, property.name), - ); - const properties = slots.map((property) => - semanticPropertyPathKeyMatches(key, property.name) - ? { + // An added slot is already unknown, so later paths that select it are inert. + const added = new Set(); + for (const [key, ...remaining] of paths.slice(reset + 1)) { + if (key === undefined || key === null) continue; + if (typeof key === "object") { + slots.forEach((property, index) => { + if (semanticPropertyPathKeyMatches(key, property.name)) + select(index, remaining); + }); + continue; + } + const indexes = slotsByName.get(String(key)); + if (indexes === undefined) added.add(String(key)); + else for (const index of indexes) select(index, remaining); + } + const properties: JavaScriptSemanticProperty[] = slots.map( + (property, index) => { + const selected = slotPaths.get(index); + return selected === undefined + ? property + : { ...property, - ...(remaining.length === 0 + ...(replacedSlots.has(index) ? { presence: "unknown-coverage" as const } : {}), - value: invalidateSemanticMutationPath(property.value, remaining), - } - : property, - ); - if (!observed && typeof key !== "object") - properties.push({ - name: String(key), - value: unknown, - presence: "unknown-coverage", - }); - return value.status === "object" - ? { ...value, properties } - : { ...value, items: properties }; - } - return unknown; + value: invalidateSemanticMutationPaths(property.value, selected), + }; + }, + ); + for (const name of added) + properties.push({ + name, + value: { + status: "unknown", + reason: "This property may have been mutated.", + }, + presence: "unknown-coverage", + }); + return base.status === "object" + ? { ...base, properties } + : { ...base, items: properties }; }; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 884915948..87f6ad540 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -10,7 +10,7 @@ import { semanticSlotAtPath } from "./javascriptSemanticSlots.js"; import { invalidateSemanticEscapedPath, - invalidateSemanticMutationPath, + invalidateSemanticMutationPaths, } from "./javascriptSemanticMutationValues.js"; import type { JavaScriptBindingProvenance } from "./javascriptSemanticIr.js"; @@ -211,13 +211,7 @@ const evaluateBinding = ( if (isPrimitive(captured)) value = captured; } } - let projected = value; - for (const path of binding.mutatedPaths) { - projected = invalidateSemanticMutationPath(projected, path); - // Every subsequent write returns this same root unknown. Replaying those - // paths at every newly collected effect otherwise becomes quadratic. - if (projected.status === "unknown") break; - } + let projected = invalidateSemanticMutationPaths(value, binding.mutatedPaths); for (const escape of binding.escapedPaths) { // Escapes only invalidate object references; other lattice values survive. if (projected.status !== "object" && projected.status !== "array") break; From c89c8f53187aac02e87f0ca11e3dd120b8c7efef Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:05:56 +0800 Subject: [PATCH 164/189] docs(mcp): record real Windows first-query recovery --- docs/mcp-contracts.md | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 70d843335..fd801cc0a 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -193,10 +193,27 @@ the current client, so it is not a fresh-start recovery. On the same connection: This close/reopen flow was exercised on one real Linux stdio connection after a controlled startup timeout, followed by a successful overview and function -analysis. It is not a Windows/macOS coverage claim. REA cleans only resources it -owns and never switches to another provider automatically. A provider timeout, -installation failure, or host permission denial needs its own reported recovery; -increasing a client deadline alone does not fix those failures. +analysis. A separate Windows x64 stdio run with Ghidra 12.1.4, JDK 21 and Node +22.19.0 exercised the same connection and caller-selected native PE: the default +60-second client request timed out, close succeeded, and reopening before a +240-second request completed the cold overview in about 163 seconds. The next +overview took about 19 ms. The cold and warm overviews reported two procedures +and two segments; the input digest was unchanged and no owned runtime root or +observed process-family member remained after final close. This was a small +1,024-byte fixture, so the longer request setting remains an example, not a +guarantee for larger targets. No macOS cold-start recovery was exercised. + +With a supplied progress token, the Windows run received an operation-start +notification before timeout and start/completion notifications for the +successful retry. It received no intermediate import or auto-analysis progress. +These operation markers do not measure analysis work completed or extend the +client's deadline. Each new provider session still imports the target into a +fresh temporary project. + +REA cleans only resources it owns and never switches to another provider +automatically. A provider timeout, installation failure, or host permission +denial needs its own reported recovery; increasing a client deadline alone does +not fix those failures. ## Tool results From 2781cad20125ff3a210b795f60620b048e1bbe9b Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:18:13 -0700 Subject: [PATCH 165/189] perf(process): stop padding rendered terminal lines to full width (#1450) Rendered frames padded every visible row with trailing spaces to the terminal width. Blank rows cost a full row each and every frame repeats them, so the padding made up 14-39% of capture Evidence (2 KB of sparse output produced 228 KB). The padding carried no information: columns is recorded and serialized_state keeps the exact terminal state. Lines are now trimmed after normalization, so line.padEnd(columns) restores the previous value. The comparison contract commits rendered_line_format so older padded captures do not compare as the same contract. Co-authored-by: Claude Opus 5.5 --- docs/process-capture.md | 6 +++ src/domain/process/processScenario.ts | 1 + src/process/capture/TerminalRenderer.test.ts | 47 +++++++++++++++++++ src/process/capture/TerminalRenderer.ts | 17 ++++--- .../processCaptureNormalization.test.ts | 1 + 5 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 src/process/capture/TerminalRenderer.test.ts diff --git a/docs/process-capture.md b/docs/process-capture.md index 1d3d23e7f..c315e3e9e 100644 --- a/docs/process-capture.md +++ b/docs/process-capture.md @@ -110,6 +110,12 @@ while comparisons and trace assertions use the normalized text. Retaining the original adds at most `limits.output_bytes` of text, because it comes from the same admitted PTY chunks rather than a second unbounded stream. +Rendered frame `lines` hold the visible rows after normalization, without +trailing spaces; pad a line to the frame's `columns` to restore the fixed-width +row. `serialized_state` keeps the exact terminal state. Captures commit this +line format in their comparison contract, so a capture whose lines were padded +to full width does not compare as the same contract. + Port normalization recognizes explicit `port`, `tcp_port`, `udp_port`, and `listen` fields, URL authorities, IP endpoints, and `localhost` endpoints, with ports from 0 through 65535. A port may end a sentence, as in `port: 8080.`; diff --git a/src/domain/process/processScenario.ts b/src/domain/process/processScenario.ts index 8312e1d2a..0ecf2c259 100644 --- a/src/domain/process/processScenario.ts +++ b/src/domain/process/processScenario.ts @@ -108,6 +108,7 @@ export const processComparisonContract = ( ...(scenario.normalization.ports ? { port_normalization_version: "contextual-endpoints-v2" } : {}), + rendered_line_format: "trailing-spaces-trimmed-v1", }); /** diff --git a/src/process/capture/TerminalRenderer.test.ts b/src/process/capture/TerminalRenderer.test.ts new file mode 100644 index 000000000..e5a19996b --- /dev/null +++ b/src/process/capture/TerminalRenderer.test.ts @@ -0,0 +1,47 @@ +import { expect, it } from "vitest"; + +import { TerminalRenderer } from "./TerminalRenderer.js"; + +const renderFrames = async ( + data: string, + normalize: (value: string) => string = (value) => value, +) => { + const renderer = new TerminalRenderer({ + columns: 20, + rows: 4, + scrollback: 10, + maxBytes: 100_000, + normalize, + }); + renderer.write(data, 0); + const frames = await renderer.frames(); + const retention = renderer.retention(); + await renderer.dispose(); + return { frames, retention }; +}; + +it("omits trailing blank cells from visible lines without losing rows", async () => { + const { frames, retention } = await renderFrames( + "left right \r\n\r\n indented", + ); + const [frame] = frames; + expect(frame?.lines).toEqual(["left right", "", " indented", ""]); + // Fixed-width rows remain recoverable from the recorded column count. + expect(frame?.lines.map((line) => line.padEnd(frame.columns, " "))).toEqual([ + "left right ", + " ".repeat(20), + " indented ", + " ".repeat(20), + ]); + expect(retention.retained_bytes).toBe( + Buffer.byteLength(frame?.serialized_state ?? "") + + Buffer.byteLength("left right indented"), + ); +}); + +it("trims only after normalization sees the full-width row", async () => { + const { frames } = await renderFrames("pid 4242", (value) => + value.replace(/4242 +$/u, ""), + ); + expect(frames[0]?.lines[0]).toBe("pid "); +}); diff --git a/src/process/capture/TerminalRenderer.ts b/src/process/capture/TerminalRenderer.ts index e7f1a0fc8..4322e2781 100644 --- a/src/process/capture/TerminalRenderer.ts +++ b/src/process/capture/TerminalRenderer.ts @@ -14,6 +14,8 @@ const HeadlessPackage = const SerializePackage = require("@xterm/addon-serialize") as typeof import("@xterm/addon-serialize"); +const TRAILING_SPACES = / +$/u; + interface TerminalRendererOptions { readonly columns: number; readonly rows: number; @@ -106,13 +108,16 @@ export class TerminalRenderer { const lines: string[] = []; for (let row = 0; row < this.#terminal.rows; row += 1) { const line = buffer.getLine(buffer.viewportY + row); + // Trailing blank cells carry no information beyond `columns`; dropping + // them keeps sparse screens from costing a full row per blank line. lines.push( - this.options.normalize( - (line?.translateToString(false, 0, this.#terminal.cols) ?? "").padEnd( - this.#terminal.cols, - " ", - ), - ), + this.options + .normalize( + ( + line?.translateToString(false, 0, this.#terminal.cols) ?? "" + ).padEnd(this.#terminal.cols, " "), + ) + .replace(TRAILING_SPACES, ""), ); } const serializedState = this.options.normalize( diff --git a/tests/boundary/process/processCaptureNormalization.test.ts b/tests/boundary/process/processCaptureNormalization.test.ts index 58cf22c0f..8156aff97 100644 --- a/tests/boundary/process/processCaptureNormalization.test.ts +++ b/tests/boundary/process/processCaptureNormalization.test.ts @@ -64,6 +64,7 @@ itWithCaptureCapability( ).toBe(true); expect(capture.manifest.comparison_contract).toMatchObject({ port_normalization_version: "contextual-endpoints-v2", + rendered_line_format: "trailing-spaces-trimmed-v1", }); expect(capture.exit).toMatchObject({ code: 0, reason: "exited" }); expect(capture.cleanup).toMatchObject({ From 696fb834b8873ac9f6df0c4d45377bdd7c3c5762 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:20:22 +0800 Subject: [PATCH 166/189] fix(skills): expose authored skill to repository discovery --- .../reverse-engineer-anything/SKILL.md | 0 .../references/android-applications.md | 0 .../references/evidence-workflows.md | 0 .../references/javascript-applications.md | 0 .../references/native-and-artifacts.md | 0 .../references/runtime-observation.md | 0 .github/pull_request_template.md | 2 +- AGENTS.md | 2 +- CONTRIBUTING.md | 8 +- docs/installation.md | 2 +- scripts/generate-package-metadata.mjs | 2 +- scripts/generate-skill-metadata.mjs | 4 +- scripts/verify-package-pack.mjs | 2 +- scripts/verify-package.mjs | 4 + scripts/verify-repository-skill.mjs | 97 +++++++++++++++++++ .../filesystem/dependencyInstall.test.ts | 2 +- .../filesystem/generatedSkill.test.ts | 2 +- turbo.json | 6 +- 18 files changed, 119 insertions(+), 14 deletions(-) rename {skill-src => .agents/skills}/reverse-engineer-anything/SKILL.md (100%) rename {skill-src => .agents/skills}/reverse-engineer-anything/references/android-applications.md (100%) rename {skill-src => .agents/skills}/reverse-engineer-anything/references/evidence-workflows.md (100%) rename {skill-src => .agents/skills}/reverse-engineer-anything/references/javascript-applications.md (100%) rename {skill-src => .agents/skills}/reverse-engineer-anything/references/native-and-artifacts.md (100%) rename {skill-src => .agents/skills}/reverse-engineer-anything/references/runtime-observation.md (100%) create mode 100644 scripts/verify-repository-skill.mjs diff --git a/skill-src/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md similarity index 100% rename from skill-src/reverse-engineer-anything/SKILL.md rename to .agents/skills/reverse-engineer-anything/SKILL.md diff --git a/skill-src/reverse-engineer-anything/references/android-applications.md b/.agents/skills/reverse-engineer-anything/references/android-applications.md similarity index 100% rename from skill-src/reverse-engineer-anything/references/android-applications.md rename to .agents/skills/reverse-engineer-anything/references/android-applications.md diff --git a/skill-src/reverse-engineer-anything/references/evidence-workflows.md b/.agents/skills/reverse-engineer-anything/references/evidence-workflows.md similarity index 100% rename from skill-src/reverse-engineer-anything/references/evidence-workflows.md rename to .agents/skills/reverse-engineer-anything/references/evidence-workflows.md diff --git a/skill-src/reverse-engineer-anything/references/javascript-applications.md b/.agents/skills/reverse-engineer-anything/references/javascript-applications.md similarity index 100% rename from skill-src/reverse-engineer-anything/references/javascript-applications.md rename to .agents/skills/reverse-engineer-anything/references/javascript-applications.md diff --git a/skill-src/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md similarity index 100% rename from skill-src/reverse-engineer-anything/references/native-and-artifacts.md rename to .agents/skills/reverse-engineer-anything/references/native-and-artifacts.md diff --git a/skill-src/reverse-engineer-anything/references/runtime-observation.md b/.agents/skills/reverse-engineer-anything/references/runtime-observation.md similarity index 100% rename from skill-src/reverse-engineer-anything/references/runtime-observation.md rename to .agents/skills/reverse-engineer-anything/references/runtime-observation.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8ffbeb73b..e33ce01f4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -28,7 +28,7 @@ intentionally not included. --> - Provider, bridge, target-format, or platform compatibility: - Evidence, artifact, provenance, or reconstruction contract: - Process execution, authorization, cleanup, or containment impact: -- Generated metadata (`docs/public/product-catalog.json`), package, or installation impact (CI generates and validates ignored catalogs and `skills/`; edit authored instructions in `skill-src/` and never commit build outputs): +- Generated metadata (`docs/public/product-catalog.json`), package, or installation impact (CI generates and validates ignored catalogs and `skills/`; edit authored instructions in `.agents/skills/reverse-engineer-anything/` and never commit build outputs): ## Evidence and regression coverage diff --git a/AGENTS.md b/AGENTS.md index 15d3984ff..6e5a2df44 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ Use [.nvmrc](.nvmrc) and `package.json#packageManager` for the pinned toolchain. Use relevant checks for the change. The complete local gate, `npm run check:pr`, is optional for broad changes or CI diagnosis. See [CONTRIBUTING.md](CONTRIBUTING.md) for development, generated-file ownership, and release conventions. -`docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored outputs. Edit source contracts and `skill-src/`, then regenerate as needed. `.cache/mcp-tool-catalog.json` is test metadata; runtime builds and source checking do not consume it. Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts. +`docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/` are ignored outputs. Edit source contracts and `.agents/skills/reverse-engineer-anything/`, then regenerate as needed. `.cache/mcp-tool-catalog.json` is test metadata; runtime builds and source checking do not consume it. Never commit binaries, provider project documents, credentials, `dist/`, `node_modules/`, or local planning artifacts. ## Tool and Test Changes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 07c71c4c5..9f4e6969b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,8 +95,12 @@ Pre-commit formats and lints staged files; pre-push runs `check:fast`. `evidence:generate` prepares only the managed commitment and its runtime/skill dependencies. The ignored outputs are `docs/public/product-catalog.json`, `docs/verification/managed-conformance-*.json`, and `skills/`. Edit authored -skill instructions in `skill-src/`. CI validates generated outputs and retains -them as artifacts; do not commit them. Reviewed source metadata, including +skill instructions in `.agents/skills/reverse-engineer-anything/`, where Skills +can discover the public bundle directly from a clean checkout. `verify:package` +installs that bundle with Skills 1.7.2 using default repository-root discovery +and checks every installed file, alongside the packaged setup checks. +CI validates generated outputs and retains them as artifacts; do not commit +them. Reviewed source metadata, including `src/generatedPackageMetadata.ts` and `docs/error-contract.schema.json`, remains tracked and checked for freshness. diff --git a/docs/installation.md b/docs/installation.md index e54cc73ae..38ea09f5a 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -95,7 +95,7 @@ npx skills add morluto/rea --skill reverse-engineer-anything This installs agent instructions and bundled references, not REA MCP registration or analysis engines. Follow the skill's -[conditional connection guide](https://github.com/morluto/rea/blob/main/skill-src/reverse-engineer-anything/SKILL.md#connect-only-when-needed). +[conditional connection guide](https://github.com/morluto/rea/blob/main/.agents/skills/reverse-engineer-anything/SKILL.md#connect-only-when-needed). Working tools can be used immediately. If tools are missing, inspect the current client's registration with `doctor --client codex --json` (substitute its client ID), then plan repairs with `setup --client codex --dry-run --json`. Show and diff --git a/scripts/generate-package-metadata.mjs b/scripts/generate-package-metadata.mjs index 8247dac1c..0130401b1 100644 --- a/scripts/generate-package-metadata.mjs +++ b/scripts/generate-package-metadata.mjs @@ -17,7 +17,7 @@ const lock = JSON.parse( await readFile(join(root, "package-lock.json"), "utf8"), ); const skill = await readFile( - join(root, "skill-src/reverse-engineer-anything/SKILL.md"), + join(root, ".agents/skills/reverse-engineer-anything/SKILL.md"), "utf8", ); const skillVersion = /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(skill)?.[1]; diff --git a/scripts/generate-skill-metadata.mjs b/scripts/generate-skill-metadata.mjs index 5bb2e3ccf..3ca0a467d 100644 --- a/scripts/generate-skill-metadata.mjs +++ b/scripts/generate-skill-metadata.mjs @@ -10,7 +10,7 @@ for (const argument of arguments_) throw new Error(`Unknown skill metadata option: ${argument}`); const root = join(dirname(fileURLToPath(import.meta.url)), ".."); -const sourceRoot = join(root, "skill-src/reverse-engineer-anything"); +const sourceRoot = join(root, ".agents/skills/reverse-engineer-anything"); const outputRoot = join(root, "skills/reverse-engineer-anything"); const check = arguments_.has("--check"); const current = ( @@ -25,7 +25,7 @@ const { PRODUCT_IDENTITY } = await import( ); if (/^\s{2}(?:tool_count|catalog_digest):/mu.test(current)) throw new Error( - "Catalog metadata belongs in the generated skill, not skill-src", + "Catalog metadata belongs in the generated skill, not the authored source", ); const versionLine = /^ {2}version: "[^"\r\n]+"$/mu; if (!versionLine.test(current)) diff --git a/scripts/verify-package-pack.mjs b/scripts/verify-package-pack.mjs index 96f05417b..fc9676745 100644 --- a/scripts/verify-package-pack.mjs +++ b/scripts/verify-package-pack.mjs @@ -38,7 +38,7 @@ export async function verifyPackagePack({ root, workspace }) { throw new Error("package did not expose both rea command entry points"); if (packedManifest.mcpName !== "io.github.morluto/rea") throw new Error("package did not retain its MCP Registry ownership marker"); - if (packedFiles.some((path) => path.startsWith("package/skill-src/"))) + if (packedFiles.some((path) => path.startsWith("package/.agents/"))) throw new Error( "package included authored skill sources instead of only the generated bundle", ); diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index 24923f7f6..b70b06064 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -17,6 +17,7 @@ import { verifyPackageMcp } from "./verify-package-mcp.mjs"; import { verifyPackagePack } from "./verify-package-pack.mjs"; import { verifyPackagePlatform } from "./verify-package-platform.mjs"; import { verifyPackageSetup } from "./verify-package-setup.mjs"; +import { verifyRepositorySkill } from "./verify-repository-skill.mjs"; import { verifyManaged } from "./verify-package-managed.mjs"; import { verifyUnknownProvider } from "./verify-package-unknown-provider.mjs"; import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs"; @@ -34,9 +35,11 @@ let tarball; let mcpStartup; let mcpModuleLoading; let update; +let repositorySkill; let report; try { + repositorySkill = await verifyRepositorySkill({ root, workspace }); ({ tarball } = await verifyPackagePack({ root, workspace })); const environmentData = await verifyPackageEnvironment({ root, @@ -156,6 +159,7 @@ try { configSymlinkLifecycle: supportedSetupHost, skill: supportedSetupHost, skillReferences: supportedSetupHost, + repositorySkill, mcpTools: TOOL_CONTRACTS.length, mcpPrompts: prompts.names.length, promptCompletion: true, diff --git a/scripts/verify-repository-skill.mjs b/scripts/verify-repository-skill.mjs new file mode 100644 index 000000000..8340bce7b --- /dev/null +++ b/scripts/verify-repository-skill.mjs @@ -0,0 +1,97 @@ +import { cp, mkdir, readFile, readdir } from "node:fs/promises"; +import { dirname, join, relative } from "node:path"; + +import { exec, pathExists } from "./lib/verify-package-core.mjs"; + +/** Exercise Skills' default root discovery without ignored build outputs. */ +export async function verifyRepositorySkill({ root, workspace }) { + const snapshot = join(workspace, "repository"); + const consumer = join(workspace, "skill-consumer"); + const home = join(workspace, "skill-consumer-home"); + const tracked = ( + await exec( + "git", + ["ls-files", "--cached", "--format=%(objectmode) %(path)", "-z"], + { cwd: root }, + ) + ).stdout + .split("\0") + .filter(Boolean); + for (const entry of tracked) { + const mode = entry.slice(0, 6); + const path = entry.slice(7); + const destination = join(snapshot, path); + // A GitHub clone without submodule initialization has only these directories. + if (mode === "160000") { + await mkdir(destination, { recursive: true }); + continue; + } + await mkdir(dirname(destination), { recursive: true }); + await cp(join(root, path), destination, { verbatimSymlinks: true }); + } + if (await pathExists(join(snapshot, "skills"))) + throw new Error("repository skill check must run without generated skills"); + await mkdir(consumer, { recursive: true }); + await mkdir(home, { recursive: true }); + const skillsVersion = "1.7.2"; + await exec( + "npm", + [ + "exec", + "--yes", + "--package", + `skills@${skillsVersion}`, + "--", + "skills", + "add", + snapshot, + "--skill", + "reverse-engineer-anything", + "--agent", + "codex", + "--yes", + ], + { + cwd: consumer, + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + XDG_CONFIG_HOME: join(home, ".config"), + CODEX_HOME: join(home, ".codex"), + DO_NOT_TRACK: "1", + SKILLS_NO_TELEMETRY: "1", + CI: "1", + }, + timeout: 120_000, + }, + ); + const authoredRoot = join( + snapshot, + ".agents/skills/reverse-engineer-anything", + ); + const installedSkills = join(consumer, ".agents/skills"); + const installedRoot = join(installedSkills, "reverse-engineer-anything"); + const files = await filePaths(authoredRoot); + if ( + JSON.stringify(await readdir(installedSkills)) !== + JSON.stringify(["reverse-engineer-anything"]) || + JSON.stringify(await filePaths(installedRoot)) !== JSON.stringify(files) + ) + throw new Error( + "Skills did not install exactly the selected public bundle", + ); + for (const path of files) { + const authored = await readFile(join(authoredRoot, path)); + if (!authored.equals(await readFile(join(installedRoot, path)))) + throw new Error(`Skills changed authored skill content: ${path}`); + } + return { skillsVersion, files }; +} + +async function filePaths(root) { + return (await readdir(root, { recursive: true, withFileTypes: true })) + .filter((entry) => entry.isFile()) + .map((entry) => relative(root, join(entry.parentPath, entry.name))) + .sort(); +} diff --git a/tests/boundary/filesystem/dependencyInstall.test.ts b/tests/boundary/filesystem/dependencyInstall.test.ts index 66378360f..806d91b32 100644 --- a/tests/boundary/filesystem/dependencyInstall.test.ts +++ b/tests/boundary/filesystem/dependencyInstall.test.ts @@ -169,7 +169,7 @@ const createBuildCacheFixture = async (): Promise => { "scripts/clean-build-output.mjs", "scripts/generate-package-metadata.mjs", "scripts/lib/generated-file.mjs", - "skill-src/reverse-engineer-anything/SKILL.md", + ".agents/skills/reverse-engineer-anything/SKILL.md", "src/generatedPackageMetadata.ts", ]; await Promise.all( diff --git a/tests/boundary/filesystem/generatedSkill.test.ts b/tests/boundary/filesystem/generatedSkill.test.ts index 5df6e3146..2b7ebf754 100644 --- a/tests/boundary/filesystem/generatedSkill.test.ts +++ b/tests/boundary/filesystem/generatedSkill.test.ts @@ -21,7 +21,7 @@ async function fixture(eol = "\n") { await mkdir(dirname(join(root, path)), { recursive: true }); await copyFile(join(repositoryRoot, path), join(root, path)); } - const sourceRoot = join(root, "skill-src/reverse-engineer-anything"); + const sourceRoot = join(root, ".agents/skills/reverse-engineer-anything"); const outputRoot = join(root, "skills/reverse-engineer-anything"); await mkdir(join(sourceRoot, "references"), { recursive: true }); await mkdir(join(root, "dist")); diff --git a/turbo.json b/turbo.json index 392523708..5b93503d7 100644 --- a/turbo.json +++ b/turbo.json @@ -39,7 +39,7 @@ "package-lock.json", "scripts/generate-package-metadata.mjs", "scripts/lib/generated-file.mjs", - "skill-src/reverse-engineer-anything/SKILL.md", + ".agents/skills/reverse-engineer-anything/SKILL.md", "src/generatedPackageMetadata.ts" ] }, @@ -138,7 +138,7 @@ "docs/**", "!docs/public/product-catalog.json", "!docs/verification/managed-conformance-*.json", - "skill-src/**", + ".agents/skills/reverse-engineer-anything/**", "README.md", { "mode": "dependencyOutputs", @@ -170,7 +170,7 @@ "package-lock.json", "scripts/generate-skill-metadata.mjs", "scripts/lib/generated-file.mjs", - "skill-src/**" + ".agents/skills/reverse-engineer-anything/**" ], "outputs": ["skills/**"] }, From ef96657d6ba0c1f22ebdb1e6bd4d9a6ac9335002 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:21:07 -0700 Subject: [PATCH 167/189] perf(javascript): hash each semantic evidence context once (#1457) The semantic graph's evidence-context registry canonicalized the full provenance context three times for every node, relation, unknown and fingerprint: once to hash its ID and twice more to compare against the stored row. A file has only a few distinct contexts, so nearly all of that work repeated a known answer. Interning now keys contexts by their canonical text. Each fact canonicalizes once, and only a new context is hashed and checked for a digest collision. IDs and output are unchanged; Obsidian's 334 MB Evidence is byte-identical and analysis drops from about 47.0 s to 44.4 s. Co-authored-by: Claude Opus 5.5 --- .../javascript/javascriptSemanticGraph.ts | 23 +++++++---- .../javascriptSemanticGraphQuery.test.ts | 40 +++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticGraph.ts b/src/domain/javascript/javascriptSemanticGraph.ts index e6cf1d530..69b3bb967 100644 --- a/src/domain/javascript/javascriptSemanticGraph.ts +++ b/src/domain/javascript/javascriptSemanticGraph.ts @@ -56,6 +56,9 @@ const evidenceContextId = (context: ApplicationGraphEvidenceContext): string => /** Graph-scoped owner for canonical provenance shared by semantic facts. */ export class JavaScriptSemanticEvidenceContextRegistry { readonly #contexts = new Map(); + // Facts share a few contexts, so key them by canonical text and hash each + // distinct context once instead of on every fact. + readonly #idsByCanonicalContext = new Map(); /** Intern normalized non-location provenance at fact construction. */ intern( @@ -63,18 +66,21 @@ export class JavaScriptSemanticEvidenceContextRegistry { ): JavaScriptSemanticEvidenceReference { const normalized = normalizeEvidence(evidence); const { location, ...context } = normalized; + const canonicalContext = canonicalJson( + context, + "JavaScript semantic graph", + ); + const internedId = this.#idsByCanonicalContext.get(canonicalContext); + if (internedId !== undefined) return { context_id: internedId, location }; const contextId = evidenceContextId(context); - const row = { ...context, context_id: contextId }; - const existing = this.#contexts.get(contextId); - if ( - existing !== undefined && - canonicalJson(existing, "JavaScript semantic graph") !== - canonicalJson(row, "JavaScript semantic graph") - ) + // This canonical context is new, so a row already stored under its + // digest holds different provenance. + if (this.#contexts.has(contextId)) throw new TypeError( "JavaScript semantic evidence context digest collision", ); - this.#contexts.set(contextId, row); + this.#contexts.set(contextId, { ...context, context_id: contextId }); + this.#idsByCanonicalContext.set(canonicalContext, contextId); return { context_id: contextId, location }; } @@ -101,6 +107,7 @@ export class JavaScriptSemanticEvidenceContextRegistry { /** Release interned contexts after the owning graph is finalized. */ clear(): void { this.#contexts.clear(); + this.#idsByCanonicalContext.clear(); } } diff --git a/src/domain/javascript/javascriptSemanticGraphQuery.test.ts b/src/domain/javascript/javascriptSemanticGraphQuery.test.ts index ddf3015f0..363cf29ad 100644 --- a/src/domain/javascript/javascriptSemanticGraphQuery.test.ts +++ b/src/domain/javascript/javascriptSemanticGraphQuery.test.ts @@ -1,6 +1,7 @@ import { expect, it } from "vitest"; import { z } from "zod"; +import { digestCanonicalValue } from "../canonicalDigest.js"; import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js"; import { JAVASCRIPT_SEMANTIC_NODE_KINDS, @@ -615,3 +616,42 @@ it.each(invalidGraphCases)( expect(issues(() => complete(steps))).toEqual(expected); }, ); + +it("interns each distinct evidence context once under its content digest", () => { + const registry = new JavaScriptSemanticEvidenceContextRegistry(); + const elsewhere: ApplicationGraphEvidence = { + ...evidence(), + location: { + available: true, + value: { + kind: "source-range", + source: "other.js", + start: { line: 7, column: 2 }, + end: { line: 7, column: 9 }, + }, + }, + }; + const first = registry.intern(evidence()); + const repeated = registry.intern(elsewhere); + const reordered = registry.intern({ + ...evidence("inferred"), + limitations: [ + "Static reachability does not prove runtime execution.", + "Static reachability does not prove runtime execution.", + ], + }); + const inferred = registry.intern(evidence("inferred")); + const { location: _location, ...context } = evidence(); + + expect(repeated.context_id).toBe(first.context_id); + expect(repeated.location).toEqual(elsewhere.location); + expect(reordered.context_id).toBe(inferred.context_id); + expect(inferred.context_id).not.toBe(first.context_id); + expect(first.context_id).toBe( + `jsrg_evidence_${digestCanonicalValue(context, "test")}`, + ); + expect(registry.contexts.map(({ context_id }) => context_id)).toEqual( + [first.context_id, inferred.context_id].toSorted(), + ); + expect(registry.resolve(repeated)).toEqual(elsewhere); +}); From b118f044926ae6b4880c4214621ae6c5b2a71f17 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:21:24 -0700 Subject: [PATCH 168/189] perf(apple): stop repeating the archive path in Interface Builder evidence (#1460) Every Interface Builder node and edge evidence record prefixed its description with the archive's relative path, which artifact_path in the same record already states. Bundles carry thousands of objects across localized nibs, so the repeated path made up 6-10% of decode_interface_builder output (XLD: 7.38 MB to 6.62 MB). Descriptions now name only the decoded item, such as "object 81" or "outlet o_quality". Co-authored-by: Claude Opus 5.5 --- .../apple/interfaceBuilderGraph.test.ts | 43 +++++++++++++++++++ src/domain/apple/interfaceBuilderGraph.ts | 4 +- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/domain/apple/interfaceBuilderGraph.test.ts b/src/domain/apple/interfaceBuilderGraph.test.ts index 13d6f79fb..fb1c0b9ad 100644 --- a/src/domain/apple/interfaceBuilderGraph.test.ts +++ b/src/domain/apple/interfaceBuilderGraph.test.ts @@ -509,3 +509,46 @@ describe("AppKit keyed archive connectors", () => { expect(to).toEqual(expect.arrayContaining(["objc_selector", "unknown"])); }); }); + +it("names the archive once per evidence record", () => { + const relativePath = "Views/Main.storyboardc/scene.nib/objects.nib"; + const result = buildInterfaceBuilderAnalysis({ + targetSha256: hash, + toolVersion: "test", + documents: [ + { + relativePath, + archiveSha256: hash, + documentKind: "storyboard_scene", + raw: { + "com.apple.ibtool.document.objects": { + controller: { customClass: "StoreViewController" }, + next: { customClass: "BuildViewController" }, + }, + "com.apple.ibtool.document.connections": { + controller: [ + { type: "segue", identifier: "showBuild", destinationId: "next" }, + ], + }, + }, + }, + ], + limits: interfaceBuilderLimitsSchema.parse({}), + }); + const evidence = [...result.graph.nodes, ...result.graph.edges].flatMap( + (item) => item.evidence, + ); + expect(new Set(evidence.map(({ artifact_path }) => artifact_path))).toEqual( + new Set([relativePath]), + ); + expect(evidence.map(({ description }) => description)).toEqual( + expect.arrayContaining([ + "compiled document", + "object controller", + "segue showBuild", + ]), + ); + expect( + evidence.filter(({ description }) => description.includes(relativePath)), + ).toEqual([]); +}); diff --git a/src/domain/apple/interfaceBuilderGraph.ts b/src/domain/apple/interfaceBuilderGraph.ts index 17e94d584..bd35130a8 100644 --- a/src/domain/apple/interfaceBuilderGraph.ts +++ b/src/domain/apple/interfaceBuilderGraph.ts @@ -72,7 +72,9 @@ export const buildInterfaceBuilderAnalysis = (input: { const evidenceFor = (description: string) => [ { kind: "interface_builder_resource" as const, - description: `${document.relativePath}: ${description}`, + // artifact_path names the archive; repeating it here cost a path per + // node and edge. + description, location: { address: null, file_offset: null }, artifact_path: document.relativePath, artifact_sha256: document.archiveSha256, From ea923287751043c7acfaa35a0acd10fe32f785d6 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:33:57 +0800 Subject: [PATCH 169/189] fix(mcp): validate doctor probe against its discovered output contract (#1461) Validate the target-free probe against the named definition discovered from the complete production catalog. Preserve initialized server and inventory observations when the SDK rejects the probe, and retain the schema failure reason, absolute deadline and owned-child cleanup. The negative stdio replay regression fails on original main and passes the fix; actual production-boundary fault injection confirms rejection. Nine doctor/help tests, serial full static checks and real small-target CLI/MCP parity pass. Successful doctor reports remain byte-identical. No performance or model-token reduction is claimed. Closes #1454. Refs #1065, #723, #1433. --- src/mcpDoctor.ts | 26 +++++++--- tests/boundary/mcp/mcpDoctor.test.ts | 77 +++++++++++++++++++++++++++- tests/fixtures/mcpDoctorReply.mjs | 48 +++++++++++++++++ 3 files changed, 144 insertions(+), 7 deletions(-) create mode 100644 tests/fixtures/mcpDoctorReply.mjs diff --git a/src/mcpDoctor.ts b/src/mcpDoctor.ts index 0f5de39fc..62a588280 100644 --- a/src/mcpDoctor.ts +++ b/src/mcpDoctor.ts @@ -6,6 +6,7 @@ import { resolve } from "node:path"; import { CATALOG_IDENTITY } from "./catalogIdentity.js"; import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js"; import { TOOL_CONTRACTS } from "./contracts/toolContracts.js"; +import { err, ok } from "./domain/result.js"; import { PRODUCT_IDENTITY } from "./identity.js"; import { MCP_STARTUP_POLICY } from "./mcpStartupPolicy.js"; @@ -131,11 +132,22 @@ const inspectProductionMcpSession = async ( signal: AbortSignal, ) => { const request = requestOptions(deadline, signal); - const [tools, prompts, requestFlow] = await Promise.all([ + const [tools, prompts] = await Promise.all([ client.listTools(undefined, request), client.listPrompts(undefined, request), - client.callTool({ name: "binary_session", arguments: {} }, request), ]); + const sessionTool = tools.tools.find(({ name }) => name === "binary_session"); + const requestFlow = await client + .callTool( + { name: "binary_session", arguments: {} }, + { + ...requestOptions(deadline, signal), + ...(sessionTool === undefined ? {} : { toolDefinition: sessionTool }), + }, + ) + .then(ok, (cause: unknown) => + err({ kind: "request-flow" as const, detail: errorMessage(cause) }), + ); const inventory = { tools: compareInventory( TOOL_CONTRACTS.map(({ name }) => name), @@ -147,7 +159,7 @@ const inspectProductionMcpSession = async ( ), }; const observedIdentity = parseIdentityToolResult( - requestFlow.structuredContent, + requestFlow.ok ? requestFlow.value.structuredContent : undefined, ); const serverVersion = client.getServerVersion(); const protocolVersion = client.getNegotiatedProtocolVersion(); @@ -173,8 +185,10 @@ const inspectProductionMcpSession = async ( }, { name: "request-flow", - ok: requestFlow.isError !== true, - detail: "binary_session target-free request", + ok: requestFlow.ok && requestFlow.value.isError !== true, + detail: requestFlow.ok + ? "binary_session target-free request" + : requestFlow.error.detail, }, ]; return { @@ -194,7 +208,7 @@ const inspectProductionMcpSession = async ( }, request_flow: { tool: "binary_session", - ok: requestFlow.isError !== true, + ok: requestFlow.ok && requestFlow.value.isError !== true, }, checks, }; diff --git a/tests/boundary/mcp/mcpDoctor.test.ts b/tests/boundary/mcp/mcpDoctor.test.ts index 9858e4ff2..e9b68b36f 100644 --- a/tests/boundary/mcp/mcpDoctor.test.ts +++ b/tests/boundary/mcp/mcpDoctor.test.ts @@ -1,4 +1,6 @@ -import { readFile } from "node:fs/promises"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { readFile, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -43,6 +45,79 @@ describe("production MCP doctor", () => { ); }, 30_000); + it("rejects a schema-invalid probe while retaining the discovered inventory", async () => { + const root = await createTestTempDirectory("rea-mcp-doctor-reply-"); + const snapshotPath = join(root, "reply.json"); + const environment = { PATH: process.env.PATH ?? "" }; + const client = new Client({ name: "doctor-reply-capture", version: "1" }); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + cwd: process.cwd(), + env: environment, + stderr: "pipe", + }); + transport.stderr?.on("data", () => undefined); + try { + await client.connect(transport); + const tools = await client.listTools(); + const prompts = await client.listPrompts(); + const toolDefinition = tools.tools.find( + ({ name }) => name === "binary_session", + ); + if (toolDefinition === undefined) + throw new Error("Production binary_session contract is missing"); + const reply = await client.callTool( + { name: "binary_session", arguments: {} }, + { toolDefinition }, + ); + await writeFile( + snapshotPath, + JSON.stringify({ + serverInfo: client.getServerVersion(), + protocolVersion: client.getNegotiatedProtocolVersion(), + tools, + prompts, + reply, + }), + ); + } finally { + await client.close(); + await transport.close(); + } + // Replay real production metadata through a synthetic stdio producer. + for (const mode of ["valid", "invalid"]) { + const result = await runProductionMcpDoctor({ + command: process.execPath, + args: [ + resolve("tests/fixtures/mcpDoctorReply.mjs"), + snapshotPath, + mode, + ], + cwd: process.cwd(), + environment, + }); + expect(result.healthy).toBe(mode === "valid"); + expect(result.inventory?.tools.observed).toBe( + CATALOG_IDENTITY.counts.mcp_tools, + ); + expect(result.inventory?.prompts.observed).toBe( + CATALOG_IDENTITY.counts.mcp_prompts, + ); + expect(result.checks).toContainEqual({ + name: "initialize", + ok: true, + detail: expect.any(String), + }); + if (mode === "invalid") + expect(result.checks).toContainEqual({ + name: "request-flow", + ok: false, + detail: expect.stringMatching(/output schema/iu), + }); + } + }, 30_000); + it("reports exact missing, unexpected, and duplicate inventory names", () => { expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({ expected: 2, diff --git a/tests/fixtures/mcpDoctorReply.mjs b/tests/fixtures/mcpDoctorReply.mjs new file mode 100644 index 000000000..14dad1240 --- /dev/null +++ b/tests/fixtures/mcpDoctorReply.mjs @@ -0,0 +1,48 @@ +import { readFile } from "node:fs/promises"; +import { createInterface } from "node:readline"; + +const snapshot = JSON.parse(await readFile(process.argv[2], "utf8")); +const reply = structuredClone(snapshot.reply); +if (process.argv[3] === "invalid") { + reply.structuredContent.schema_violation_control = true; + reply.content = reply.content.map((item) => + item.type === "text" + ? { ...item, text: JSON.stringify(reply.structuredContent) } + : item, + ); +} + +const input = createInterface({ input: process.stdin }); +input.on("line", (line) => { + const request = JSON.parse(line); + if (request.id === undefined) return; + let result; + switch (request.method) { + case "initialize": + result = { + protocolVersion: snapshot.protocolVersion, + capabilities: { tools: {}, prompts: {} }, + serverInfo: snapshot.serverInfo, + }; + break; + case "tools/list": + result = snapshot.tools; + break; + case "prompts/list": + result = snapshot.prompts; + break; + case "tools/call": + if (request.params.name === "binary_session") result = reply; + break; + case "ping": + result = {}; + break; + } + const response = + result === undefined + ? { error: { code: -32601, message: "Unknown fixture method or tool" } } + : { result }; + process.stdout.write( + `${JSON.stringify({ jsonrpc: "2.0", id: request.id, ...response })}\n`, + ); +}); From 4e3d3354397374116577555200319975fc2ff86e Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:37:49 +0800 Subject: [PATCH 170/189] test(android): retain incomplete cleanup failure reasons (#1443) Include the full stop disposition in the fixture assertion message, so incomplete owned teardown retains its typed reason in Vitest failure reporters. Preserve the existing cleanup requirement without retries or relaxed ownership checks. Seven process-boundary tests, full serial typecheck/lint/duplication/format checks, and 19 final-head CI checks pass after integrating the combined-main fixture fix. A controlled failure-rendering probe verifies that the explicit message preserves the reason. The original CI cleanup failure remains unreproduced; this is diagnostic work with a synthetic JADX producer, not a root-cause or real-engine fix. Refs #1441, #1446, #1448, #1065. --- tests/fixtures/android/jadx.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/fixtures/android/jadx.ts b/tests/fixtures/android/jadx.ts index 3488647a0..c82469039 100644 --- a/tests/fixtures/android/jadx.ts +++ b/tests/fixtures/android/jadx.ts @@ -74,7 +74,10 @@ export const createJadxProtocolFixture = async ( ownsProcessLifetime: true, cleanup: () => cleanupOwnedProcessGroup(spawned.ownership), }); - expect((await supervisor.stop()).status).not.toBe("incomplete"); + const stopped = await supervisor.stop(); + expect(stopped, JSON.stringify(stopped)).not.toMatchObject({ + status: "incomplete", + }); if (options.cwd !== undefined) await rm(options.cwd, { recursive: true, force: true }); }); From 78e1308f49492011be448c9b35ce16d98d60c4ad Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:58:15 +0800 Subject: [PATCH 171/189] docs(process): clarify normalized terminal line representation --- docs/process-capture.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/process-capture.md b/docs/process-capture.md index c315e3e9e..5cc246ec2 100644 --- a/docs/process-capture.md +++ b/docs/process-capture.md @@ -110,11 +110,14 @@ while comparisons and trace assertions use the normalized text. Retaining the original adds at most `limits.output_bytes` of text, because it comes from the same admitted PTY chunks rather than a second unbounded stream. -Rendered frame `lines` hold the visible rows after normalization, without -trailing spaces; pad a line to the frame's `columns` to restore the fixed-width -row. `serialized_state` keeps the exact terminal state. Captures commit this -line format in their comparison contract, so a capture whose lines were padded -to full width does not compare as the same contract. +Rendered frame `lines` hold the visible rows after normalization, with trailing +U+0020 spaces removed. Blank rows and internal spaces remain. `columns` records +terminal cell width; normalization and Unicode can make string lengths differ +from that width. `serialized_state` holds terminal serialization after the +selected normalization. Original admitted PTY chunks are available through +`raw_data ?? data`, as described above. Captures commit this line format in their +comparison contract, so a capture whose lines were padded to full width does not +compare as the same contract. Port normalization recognizes explicit `port`, `tcp_port`, `udp_port`, and `listen` fields, URL authorities, IP endpoints, and `localhost` endpoints, with From 79f6756239105164eac7aa5618844ffd9bdf41e5 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:00:09 -0700 Subject: [PATCH 172/189] docs(website): link the Discord community and REA on X (#1469) Add an X link beside the GitHub and Discord header icons on every content page, name the footer links "Join the community" and "Follow us on X", and close the homepage with a "Join the community" section. On narrow screens, pad the footer so the floating Top link no longer covers its last row of links. Co-authored-by: Claude Opus 5.5 --- website/README.md | 4 +- website/public/assets/styles.css | 12 ++++-- website/public/examples/dino-lab/index.html | 22 +++++++++- website/public/faq/index.html | 22 +++++++++- website/public/first-investigation/index.html | 22 +++++++++- website/public/get-started/index.html | 22 +++++++++- website/public/guides/browser/index.html | 22 +++++++++- website/public/guides/index.html | 22 +++++++++- website/public/guides/javascript/index.html | 22 +++++++++- website/public/guides/native/index.html | 22 +++++++++- website/public/index.html | 40 ++++++++++++++++++- website/public/showcase/aegis/index.html | 22 +++++++++- website/public/showcase/ctf/index.html | 22 +++++++++- website/public/showcase/dx-ball/index.html | 22 +++++++++- website/public/showcase/index.html | 22 +++++++++- website/public/showcase/notion/index.html | 22 +++++++++- website/public/showcase/th04/index.html | 22 +++++++++- 17 files changed, 345 insertions(+), 19 deletions(-) diff --git a/website/README.md b/website/README.md index 2005c633d..4262ccb24 100644 --- a/website/README.md +++ b/website/README.md @@ -181,7 +181,9 @@ the analysis guides. Case-study previews live on the Showcases page. The closing section offers copyable project prompts, from cloning `rea.tools` to reconstructing a game from its executable. The experienced-reader shortcut lands directly on the guide links below these prompts. -The page ends with FAQ, Discord and issue-report links under “Any questions?”. +“Any questions?” offers FAQ, Discord and issue-report links. The page ends +with “Join the community”, which links Discord and REA's X account. +Every content page's header and footer link GitHub, Discord and X. A right-side table of contents stays visible at widths of 1440px and above. On narrower screens it becomes a sticky, native disclosure; selecting a link closes the menu and focuses the destination. The homepage script follows diff --git a/website/public/assets/styles.css b/website/public/assets/styles.css index fb7093b9e..2020fd5f8 100644 --- a/website/public/assets/styles.css +++ b/website/public/assets/styles.css @@ -178,7 +178,8 @@ section[id] { gap: 8px; } .nav-github, -.nav-discord { +.nav-discord, +.nav-x { display: inline-flex; align-items: center; justify-content: center; @@ -192,12 +193,14 @@ section[id] { text-decoration: none; } .nav-github:hover, -.nav-discord:hover { +.nav-discord:hover, +.nav-x:hover { background: var(--soft); color: var(--ink); } .nav-github svg, -.nav-discord svg { +.nav-discord svg, +.nav-x svg { display: block; flex-shrink: 0; } @@ -2117,6 +2120,9 @@ pre code { right: calc(1rem + env(safe-area-inset-right, 0px)); bottom: calc(1rem + env(safe-area-inset-bottom, 0px)); } + .site-footer { + padding-bottom: calc(2rem + 44px + env(safe-area-inset-bottom, 0px)); + } .container { width: calc(100% - 2.5rem); } diff --git a/website/public/examples/dino-lab/index.html b/website/public/examples/dino-lab/index.html index bfae79460..d0bc84c76 100644 --- a/website/public/examples/dino-lab/index.html +++ b/website/public/examples/dino-lab/index.html @@ -107,6 +107,25 @@ /> + + + @@ -383,7 +402,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/faq/index.html b/website/public/faq/index.html index 60fe1183d..fa4a64a83 100644 --- a/website/public/faq/index.html +++ b/website/public/faq/index.html @@ -107,6 +107,25 @@ /> + + + @@ -482,7 +501,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/first-investigation/index.html b/website/public/first-investigation/index.html index 349ece913..a642735c2 100644 --- a/website/public/first-investigation/index.html +++ b/website/public/first-investigation/index.html @@ -106,6 +106,25 @@ /> + + + @@ -420,7 +439,8 @@ JS SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/get-started/index.html b/website/public/get-started/index.html index b86987e9e..d13ad67ba 100644 --- a/website/public/get-started/index.html +++ b/website/public/get-started/index.html @@ -106,6 +106,25 @@ /> + + + @@ -479,7 +498,8 @@ npx rea-agents@latest setup SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/guides/browser/index.html b/website/public/guides/browser/index.html index 95a0aaaae..b1567f9f1 100644 --- a/website/public/guides/browser/index.html +++ b/website/public/guides/browser/index.html @@ -100,6 +100,25 @@ /> + + + @@ -403,7 +422,8 @@ link.click(); SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/guides/index.html b/website/public/guides/index.html index babd58bdf..eeed0e7f1 100644 --- a/website/public/guides/index.html +++ b/website/public/guides/index.html @@ -100,6 +100,25 @@ /> + + + @@ -186,7 +205,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/guides/javascript/index.html b/website/public/guides/javascript/index.html index 5212b579d..8e77022fe 100644 --- a/website/public/guides/javascript/index.html +++ b/website/public/guides/javascript/index.html @@ -106,6 +106,25 @@ /> + + + @@ -405,7 +424,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/guides/native/index.html b/website/public/guides/native/index.html index a0e19caf5..f3c4a658a 100644 --- a/website/public/guides/native/index.html +++ b/website/public/guides/native/index.html @@ -100,6 +100,25 @@ /> + + + @@ -335,7 +354,8 @@ return (DxBallInt)pan; SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/index.html b/website/public/index.html index 0282d64de..11d70c1d9 100644 --- a/website/public/index.html +++ b/website/public/index.html @@ -109,6 +109,25 @@ /> + + + @@ -134,6 +153,7 @@
  • Try REA
  • Go deeper
  • Help & feedback
  • +
  • Community
  • @@ -1052,6 +1072,23 @@ SPEED: 6

    +
    +
    +

    Join the community

    +

    + Share investigations and get help from other REA users on Discord. + Follow REA on X for project updates. +

    + +
    +
    diff --git a/website/public/showcase/aegis/index.html b/website/public/showcase/aegis/index.html index 05a230501..7949addfd 100644 --- a/website/public/showcase/aegis/index.html +++ b/website/public/showcase/aegis/index.html @@ -108,6 +108,25 @@ /> + + + @@ -718,7 +737,8 @@ npx rea-agents@latest inspect-android-package \ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/showcase/ctf/index.html b/website/public/showcase/ctf/index.html index ed2002924..afe735fee 100644 --- a/website/public/showcase/ctf/index.html +++ b/website/public/showcase/ctf/index.html @@ -107,6 +107,25 @@ /> + + + @@ -688,7 +707,8 @@ chmod +x ms_flag_checker SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/showcase/dx-ball/index.html b/website/public/showcase/dx-ball/index.html index d47449978..d89d2bf5b 100644 --- a/website/public/showcase/dx-ball/index.html +++ b/website/public/showcase/dx-ball/index.html @@ -107,6 +107,25 @@ /> + + + @@ -696,7 +715,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/showcase/index.html b/website/public/showcase/index.html index f0a537f69..168afcde9 100644 --- a/website/public/showcase/index.html +++ b/website/public/showcase/index.html @@ -107,6 +107,25 @@ /> + + + @@ -228,7 +247,8 @@ SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/showcase/notion/index.html b/website/public/showcase/notion/index.html index 5120d8ca6..c276d16c9 100644 --- a/website/public/showcase/notion/index.html +++ b/website/public/showcase/notion/index.html @@ -107,6 +107,25 @@ /> + + + @@ -534,7 +553,8 @@ mimeTypes: SourceMIT licenseCommunity + >Join the communityFollow us on X diff --git a/website/public/showcase/th04/index.html b/website/public/showcase/th04/index.html index e08f8f2a3..9a89af639 100644 --- a/website/public/showcase/th04/index.html +++ b/website/public/showcase/th04/index.html @@ -107,6 +107,25 @@ /> + + + @@ -711,7 +730,8 @@ no_aim: SourceMIT licenseCommunity + >Join the communityFollow us on X From 934ffd28d15f4fbe6687ca8986a949e1b41a07d1 Mon Sep 17 00:00:00 2001 From: keemsisi Date: Sat, 10 Oct 2026 08:09:18 +0100 Subject: [PATCH 173/189] perf(javascript): derive the application graph ID once createJavaScriptApplicationGraph hashed the whole graph to derive its graph_id, then parsed it with the public schema, whose invariant check hashed the same content again to verify that ID. Validate the content with every other invariant first, then derive graph_id once from the validated copy. The public schema still verifies graph_id for stored and untrusted graphs, and created graphs are unchanged. --- .../javascriptApplicationGraph.test.ts | 15 +++++++++++++ .../javascript/javascriptApplicationGraph.ts | 22 ++++++++++++++----- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/domain/javascript/javascriptApplicationGraph.test.ts b/src/domain/javascript/javascriptApplicationGraph.test.ts index efedf78c0..58f127928 100644 --- a/src/domain/javascript/javascriptApplicationGraph.test.ts +++ b/src/domain/javascript/javascriptApplicationGraph.test.ts @@ -547,6 +547,21 @@ describe("JavaScript Application Graph: source maps and observations", () => { /Edge identifier/u, ); }); + + it("creates exactly the graph the public schema accepts", () => { + const graph = buildSyntheticJavaScriptApplicationGraph(); + expect(JSON.stringify(graph)).toBe( + JSON.stringify( + javascriptApplicationGraphSchema.parse(structuredClone(graph)), + ), + ); + + const { graph_id: _graphId, ...semantic } = structuredClone(graph); + firstOf(semantic.edges, "edge").edge_id = `jag_edge_${"f".repeat(64)}`; + expect(() => createJavaScriptApplicationGraph(semantic)).toThrow( + /Edge identifier/u, + ); + }); }); describe("JavaScript Application Graph: duplicate and orphan rejection", () => { diff --git a/src/domain/javascript/javascriptApplicationGraph.ts b/src/domain/javascript/javascriptApplicationGraph.ts index ba122e1f0..e16aded75 100644 --- a/src/domain/javascript/javascriptApplicationGraph.ts +++ b/src/domain/javascript/javascriptApplicationGraph.ts @@ -304,8 +304,8 @@ const checkNode = ( type GraphRecord = z.infer; -const checkGraphInvariants = ( - graph: GraphRecord, +const checkGraphContent = ( + graph: JavaScriptApplicationGraphInput, context: z.RefinementCtx, ): void => { sortedUniqueIssue( @@ -394,7 +394,13 @@ const checkGraphInvariants = ( context, ); } +}; +const checkGraphInvariants = ( + graph: GraphRecord, + context: z.RefinementCtx, +): void => { + checkGraphContent(graph, context); const { graph_id: identifier, ...semantic } = graph; if ( identifier !== @@ -411,6 +417,9 @@ const checkGraphInvariants = ( export const javascriptApplicationGraphSchema = javascriptApplicationGraphRecordSchema.superRefine(checkGraphInvariants); +const javascriptApplicationGraphContentSchema = + javascriptApplicationGraphInputSchema.superRefine(checkGraphContent); + /** Fully validated JavaScript Application Graph. */ export type JavaScriptApplicationGraph = z.infer< typeof javascriptApplicationGraphSchema @@ -482,10 +491,11 @@ export const createJavaScriptApplicationGraph = ( }, limitations: uniqueSorted(parsed.limitations), }; - return javascriptApplicationGraphSchema.parse({ - ...semantic, - graph_id: `jag_${digestCanonicalValue(semantic, "JavaScript Application Graph")}`, - }); + const content = javascriptApplicationGraphContentSchema.parse(semantic); + return { + ...content, + graph_id: `jag_${digestCanonicalValue(content, "JavaScript Application Graph")}`, + }; }; const validatedImmutableApplicationGraphs = new WeakSet(); From aa23ec883f6c7101db184767a1f48cddb636d597 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=93=E8=89=AF?= <1204183885@qq.com> Date: Sat, 10 Oct 2026 15:12:09 +0800 Subject: [PATCH 174/189] feat(clients): register Qwen Code during setup (#1415) * feat(clients): register Qwen Code during setup * fix(clients): honor Qwen home and shared skill discovery --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/installation.md | 15 +- scripts/verify-package-environment.mjs | 1 + src/application/ClientRegistrationStatus.ts | 1 + src/application/SupportedClients.ts | 31 ++- .../filesystem/clientLifecycle.test.ts | 1 + .../qwenClientConfiguration.test.ts | 183 ++++++++++++++++++ tests/fixtures/clientEnvironment.ts | 1 + 7 files changed, 228 insertions(+), 5 deletions(-) create mode 100644 tests/boundary/filesystem/qwenClientConfiguration.test.ts diff --git a/docs/installation.md b/docs/installation.md index 38ea09f5a..acc285e69 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -135,10 +135,17 @@ listed after the table because its connector is not one of these files: | Antigravity | `antigravity` | | GitHub Copilot CLI | `copilot_cli` | | Command Code | `commandcode` | +| Qwen Code | `qwen_code` | | VS Code | `vscode` | | Grok Build | `grok_build` | | OMP | `omp` | +For Qwen Code, setup registers `rea` in the `mcpServers` table of the +user-level `~/.qwen/settings.json`, or `$QWEN_HOME/settings.json` when configured. +Setup and doctor follow Qwen Code's tilde and working-directory-relative home +overrides. Qwen Code also discovers personal skills in `~/.agents/skills`, +where setup installs the bundled workflow. + For OMP, setup writes a `type: "stdio"` entry to the user-level `~/.omp/agent/mcp.json`. It follows `PI_CONFIG_DIR`, an absolute `PI_CODING_AGENT_DIR`, and the profile selected by `OMP_PROFILE` or @@ -194,10 +201,10 @@ save verified paths for an existing Ghidra installation. The bundled skill is installed where each selected client discovers personal skills: Claude Code uses `~/.claude/skills` (or -`$CLAUDE_CONFIG_DIR/skills` when configured), while other supported clients -use the shared `~/.agents/skills` directory. A mixed selection plans both -paths. Selecting the skill without a client uses the shared directory. Setup -leaves existing skill copies in other locations untouched. +`$CLAUDE_CONFIG_DIR/skills` when configured), while other supported clients, +including Qwen Code, use the shared `~/.agents/skills` directory. A mixed selection +plans the relevant paths. Selecting the skill without a client uses the shared +directory. Setup leaves existing skill copies in other locations untouched. `doctor --skill --json` verifies the selected copies against the bundled instructions and references. Consumers should use `identity.skill.state`, diff --git a/scripts/verify-package-environment.mjs b/scripts/verify-package-environment.mjs index f9ee010af..1a97cfbab 100644 --- a/scripts/verify-package-environment.mjs +++ b/scripts/verify-package-environment.mjs @@ -85,6 +85,7 @@ export async function verifyPackageEnvironment({ PI_CODING_AGENT_DIR: undefined, PI_CONFIG_DIR: undefined, PI_PROFILE: undefined, + QWEN_HOME: undefined, OPENCODE_CONFIG: undefined, XDG_CONFIG_HOME: join(home, ".config"), PATH: `${fakeBin}:${process.env.PATH ?? ""}`, diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index a657f1df4..1f5a12473 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -91,6 +91,7 @@ export const readClientRegistrationStatuses = async ( PI_CODING_AGENT_DIR: options.environment.PI_CODING_AGENT_DIR, PI_CONFIG_DIR: options.environment.PI_CONFIG_DIR, PI_PROFILE: options.environment.PI_PROFILE, + QWEN_HOME: options.environment.QWEN_HOME, SAND_DATA_ROOT: options.environment.SAND_DATA_ROOT, XDG_CONFIG_HOME: options.environment.XDG_CONFIG_HOME, }, diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 97467a227..52f5577ca 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -1,4 +1,4 @@ -import { isAbsolute, join } from "node:path"; +import { isAbsolute, join, resolve } from "node:path"; import { lstatSync } from "node:fs"; /** One supported client configuration location. */ @@ -35,6 +35,7 @@ interface ClientPathContext { readonly PI_CODING_AGENT_DIR?: string | undefined; readonly PI_CONFIG_DIR?: string | undefined; readonly PI_PROFILE?: string | undefined; + readonly QWEN_HOME?: string | undefined; readonly SAND_DATA_ROOT?: string | undefined; readonly XDG_CONFIG_HOME?: string | undefined; }; @@ -85,6 +86,25 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string => const codexDirectory = ({ home, env }: ClientPathContext): string => env.CODEX_HOME ?? join(home, ".codex"); +/** Match Qwen Code's home override, including tilde and cwd-relative paths. */ +const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => { + const override = env.QWEN_HOME; + if (!override) return join(home, ".qwen"); + const expanded = + override === "~" + ? home + : override.startsWith("~/") || override.startsWith("~\\") + ? join( + home, + ...override + .slice(2) + .split(/[/\\]+/) + .filter(Boolean), + ) + : override; + return isAbsolute(expanded) ? expanded : resolve(expanded); +}; + const grokDirectory = ({ home, env }: ClientPathContext): string => env.GROK_HOME ?? join(home, ".grok"); @@ -272,6 +292,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ markerPath: commandCodeDirectory, format: "commandcode", }, + { + name: "qwen_code", + displayName: "Qwen Code", + configPath: (context: ClientPathContext) => + join(qwenCodeDirectory(context), "settings.json"), + markerPath: qwenCodeDirectory, + format: "json", + }, { name: "vscode", displayName: "VS Code", @@ -323,6 +351,7 @@ export const supportedClients = ( PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR, PI_CONFIG_DIR: process.env.PI_CONFIG_DIR, PI_PROFILE: process.env.PI_PROFILE, + QWEN_HOME: process.env.QWEN_HOME, SAND_DATA_ROOT: process.env.SAND_DATA_ROOT, XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME, }, diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts index 88eab9953..297787a10 100644 --- a/tests/boundary/filesystem/clientLifecycle.test.ts +++ b/tests/boundary/filesystem/clientLifecycle.test.ts @@ -59,6 +59,7 @@ describe("client configuration filesystem lifecycle", () => { "antigravity", "copilot_cli", "commandcode", + "qwen_code", "vscode", "grok_build", "omp", diff --git a/tests/boundary/filesystem/qwenClientConfiguration.test.ts b/tests/boundary/filesystem/qwenClientConfiguration.test.ts new file mode 100644 index 000000000..0fae29640 --- /dev/null +++ b/tests/boundary/filesystem/qwenClientConfiguration.test.ts @@ -0,0 +1,183 @@ +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { parse as parseJsonc } from "jsonc-parser"; + +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js"; +import { systemSetupHost } from "../../../src/application/SetupHost.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { systemUninstallHost } from "../../../src/application/Uninstall.js"; +import { PRODUCT_IDENTITY } from "../../../src/identity.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + clearClientLocationEnvironment, + NPX_REGISTRATION_COMMAND, +} from "../../fixtures/clientEnvironment.js"; + +const command = NPX_REGISTRATION_COMMAND; + +beforeEach(clearClientLocationEnvironment); +afterEach(() => vi.unstubAllEnvs()); + +const qwenPath = ( + home: string, + platform: NodeJS.Platform, + env: Parameters[2] = {}, +) => + supportedClients(home, platform, env).find( + ({ name }) => name === "qwen_code", + ); + +describe("Qwen Code configuration paths", () => { + it("resolves the user settings file and marker directory", () => { + expect(qwenPath("/home/a", "linux")).toEqual({ + name: "qwen_code", + displayName: "Qwen Code", + configPath: join("/home/a", ".qwen", "settings.json"), + markerPath: join("/home/a", ".qwen"), + format: "json", + }); + expect(qwenPath("/Users/a", "darwin")?.configPath).toBe( + join("/Users/a", ".qwen", "settings.json"), + ); + }); + + it.each([ + ["", join("/home/a", ".qwen")], + ["~", "/home/a"], + ["~/profiles/work", join("/home/a", "profiles", "work")], + ["~\\profiles\\work", join("/home/a", "profiles", "work")], + ["profiles/work", resolve("profiles/work")], + [" profile ", resolve(" profile ")], + ["$PROFILE", resolve("$PROFILE")], + ])("matches Qwen's QWEN_HOME resolution for %j", (override, directory) => { + vi.stubEnv("QWEN_HOME", override); + const client = qwenPath("/home/a", process.platform, { + QWEN_HOME: override, + }); + expect( + supportedClients("/home/a").find(({ name }) => name === "qwen_code"), + ).toEqual(client); + expect(client).toMatchObject({ + configPath: join(directory, "settings.json"), + markerPath: directory, + }); + }); +}); + +describe("Qwen Code client lifecycle", () => { + const qwenClient = async () => { + const home = await createTestTempDirectory("rea-qwen-"); + const client = qwenPath(home, process.platform, {}); + if (client?.markerPath === undefined) + throw new Error("missing Qwen Code client"); + await mkdir(client.markerPath, { recursive: true }); + return { home, client }; + }; + + it("registers rea in mcpServers while preserving unrelated settings and comments", async () => { + const { home, client } = await qwenClient(); + await writeFile( + client.configPath, + `{ + // Keep this note. + "model": { "name": "qwen3-coder-plus" }, + "mcpServers": { "other": { "command": "other-server" } } +} +`, + ); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + const text = await readFile(client.configPath, "utf8"); + expect(text).toContain("// Keep this note."); + expect(parseJsonc(text)).toEqual({ + model: { name: "qwen3-coder-plus" }, + mcpServers: { + other: { command: "other-server" }, + rea: { command: "npx", args: command.slice(1) }, + }, + }); + expect(await configureClientConfiguration(client, {}, command)).toEqual({ + status: "unchanged", + }); + expect((await systemUninstallHost(home).removeClient(client)).status).toBe( + "removed", + ); + const removedText = await readFile(client.configPath, "utf8"); + const removed = parseJsonc(removedText); + expect(removed).toEqual({ + model: { name: "qwen3-coder-plus" }, + mcpServers: { other: { command: "other-server" } }, + }); + expect(removedText).toContain("// Keep this note."); + }); + + it("reports a package-runner registration as aligned", async () => { + const { home, client } = await qwenClient(); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + const entry = resolve("scripts/rea.mjs"); + const status = ( + await readClientRegistrationStatuses(home, entry, { environment: {} }) + ).find(({ client: name }) => name === "qwen_code"); + expect(status).toMatchObject({ state: "aligned" }); + }); +}); + +describe("Qwen Code profile setup", () => { + it.each([false, true])( + "installs and removes the shared skill with a custom home: %s", + async (customHome) => { + const home = await createTestTempDirectory("rea-qwen-profile-"); + const profile = join(home, customHome ? "qwen-profile" : ".qwen"); + const environment = { + HOME: home, + USERPROFILE: home, + ...(customHome ? { QWEN_HOME: profile } : {}), + }; + await mkdir(profile); + const setup = systemSetupHost(undefined, environment); + const client = (await setup.detectedClients()).find( + ({ name }) => name === "qwen_code", + ); + if (client === undefined) throw new Error("missing Qwen Code client"); + expect(client.configPath).toBe(join(profile, "settings.json")); + expect(await setup.configureClient(client, {}, command)).toEqual({ + status: "configured", + }); + expect(await setup.installSkill([client.name])).toBe("installed"); + const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName); + expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain( + "reverse-engineer-anything", + ); + expect(await setup.clientNeedsConfigure(client, {}, command)).toBe(false); + expect(await setup.skillNeedsInstall([client.name])).toBe(false); + expect(await setup.installSkill([client.name])).toBe("unchanged"); + expect( + ( + await readClientRegistrationStatuses( + home, + resolve("scripts/rea.mjs"), + { environment }, + ) + ).find(({ client: name }) => name === "qwen_code"), + ).toMatchObject({ state: "aligned" }); + const uninstall = systemUninstallHost(home, undefined, environment); + const registered = (await uninstall.clients()).find( + ({ name }) => name === "qwen_code", + ); + expect(registered).toEqual(client); + expect((await uninstall.removeClient(client)).status).toBe("removed"); + expect((await uninstall.removeSkill()).status).toBe("removed"); + await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" }); + if (customHome) + await expect(access(join(home, ".qwen"))).rejects.toMatchObject({ + code: "ENOENT", + }); + }, + ); +}); diff --git a/tests/fixtures/clientEnvironment.ts b/tests/fixtures/clientEnvironment.ts index 79961e49d..0db5a69ec 100644 --- a/tests/fixtures/clientEnvironment.ts +++ b/tests/fixtures/clientEnvironment.ts @@ -22,6 +22,7 @@ export const CLIENT_LOCATION_ENVIRONMENT = [ "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "PI_PROFILE", + "QWEN_HOME", "SAND_DATA_ROOT", "XDG_CONFIG_HOME", ] as const; From 3c7b176a3df18b3971d9ea9ff40f7ebbd85fa40a Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:12:17 -0700 Subject: [PATCH 175/189] perf(artifacts): deliver the inspected artifact graph once (#1473) inspect_artifact nested the complete inventory Evidence and then restated every artifact node and occurrence as an observation and every edge as a derived relationship. No caller reads those copies; comparison and tests use the nested inventory Evidence. On Transmission.app the result shrinks from 2.46 MB to 1.10 MB. Observations keep the root manifest and integrity findings. Co-authored-by: Claude Opus 5.5 --- src/contracts/artifactToolContracts.ts | 2 +- src/domain/artifactInspection.ts | 59 +------------------ .../artifactProvider.archiveInventory.test.ts | 9 +++ 3 files changed, 13 insertions(+), 57 deletions(-) diff --git a/src/contracts/artifactToolContracts.ts b/src/contracts/artifactToolContracts.ts index a6926a19f..744ea34c3 100644 --- a/src/contracts/artifactToolContracts.ts +++ b/src/contracts/artifactToolContracts.ts @@ -63,7 +63,7 @@ const artifact = < export const ARTIFACT_TOOL_CONTRACTS = [ artifact( "inspect_artifact", - "Inspect an active archive or application package in one call. Returns the complete content-addressed artifact graph, source Evidence, observations, relationships, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.", + "Inspect an active archive or application package in one call. Returns the complete content-addressed artifact graph once, as the nested inventory Evidence, with root and integrity observations, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.", artifactInventoryInputSchema, ), artifact( diff --git a/src/domain/artifactInspection.ts b/src/domain/artifactInspection.ts index f4c197b9c..19ccb9b8f 100644 --- a/src/domain/artifactInspection.ts +++ b/src/domain/artifactInspection.ts @@ -16,30 +16,12 @@ const artifactIdSchema = prefixedDigestSchema("art"); const inspectionObservationSchema = z.strictObject({ observation_id: prefixedDigestSchema("aio"), - kind: z.enum(["root-manifest", "artifact", "occurrence", "integrity"]), + kind: z.enum(["root-manifest", "integrity"]), subject: textSchema, value: jsonValueSchema, evidence_id: evidenceIdSchema, }); -const inspectionRelationshipSchema = z.strictObject({ - relationship_id: prefixedDigestSchema("air"), - relation: z.enum([ - "contains", - "extracts", - "slice-of", - "embeds", - "loads", - "maps-source", - "derived-from", - ]), - source_artifact_id: artifactIdSchema, - target_artifact_id: artifactIdSchema, - occurrence_id: prefixedDigestSchema("occ"), - logical_path: textSchema.nullable(), - evidence_id: evidenceIdSchema, -}); - const inspectionHypothesisSchema = z.strictObject({ hypothesis_id: prefixedDigestSchema("aih"), statement: textSchema, @@ -97,7 +79,6 @@ export const artifactInspectionResultSchema = z.strictObject({ ) .min(1), observations: z.array(inspectionObservationSchema), - derived_relationships: z.array(inspectionRelationshipSchema), hypotheses: z.array(inspectionHypothesisSchema), contradictions: z.array(inspectionContradictionSchema), unexplored_branches: z.array(unexploredBranchSchema), @@ -107,8 +88,6 @@ export const artifactInspectionResultSchema = z.strictObject({ substeps_completed: z.literal(1), observations_retained: z.number().int().min(0), observations_omitted: z.number().int().min(0), - relationships_retained: z.number().int().min(0), - relationships_omitted: z.number().int().min(0), hypotheses_retained: z.number().int().min(0), hypotheses_omitted: z.number().int().min(0), unexplored_branches_retained: z.number().int().min(0), @@ -136,10 +115,6 @@ export const createArtifactInspection = ( inventory, inventoryEvidence.evidence_id, ); - const relationships = allRelationships( - inventory, - inventoryEvidence.evidence_id, - ); const hypotheses = allHypotheses(inventory, inventoryEvidence.evidence_id); const nextProbes = probesFor(inventory); const branches = allUnexploredBranches( @@ -149,14 +124,12 @@ export const createArtifactInspection = ( ); const retained = { observations, - relationships, hypotheses, branches, probes: nextProbes, }; const omissions = { observations: 0, - relationships: 0, hypotheses: 0, branches: 0, probes: 0, @@ -184,7 +157,6 @@ export const createArtifactInspection = ( }, ], observations: retained.observations, - derived_relationships: retained.relationships, hypotheses: retained.hypotheses, contradictions: contradictions(inventory, inventoryEvidence.evidence_id), unexplored_branches: retained.branches, @@ -194,8 +166,6 @@ export const createArtifactInspection = ( substeps_completed: 1 as const, observations_retained: retained.observations.length, observations_omitted: omissions.observations, - relationships_retained: retained.relationships.length, - relationships_omitted: omissions.relationships, hypotheses_retained: retained.hypotheses.length, hypotheses_omitted: omissions.hypotheses, unexplored_branches_retained: retained.branches.length, @@ -224,6 +194,8 @@ const parseInventoryEvidence = (input: unknown): Evidence => { return evidence; }; +// Artifact, occurrence, and edge records stay in the nested inventory Evidence; +// restating each one here would repeat the complete graph in every result. const allObservations = ( inventory: ArtifactInventoryResult, evidenceId: string, @@ -234,12 +206,6 @@ const allObservations = ( inventory.manifest, evidenceId, ), - ...inventory.nodes.map((node) => - observation("artifact", node.artifact_id, node, evidenceId), - ), - ...inventory.occurrences.map((occurrence) => - observation("occurrence", occurrence.occurrence_id, occurrence, evidenceId), - ), ...inventory.integrity_contradictions.map((value) => observation("integrity", value.contradiction_id, value, evidenceId), ), @@ -263,25 +229,6 @@ const observation = ( }; }; -const allRelationships = ( - inventory: ArtifactInventoryResult, - evidenceId: string, -): ArtifactInspectionResult["derived_relationships"] => - inventory.edges.map((edge) => { - const semantic = { - relation: edge.relation, - source_artifact_id: edge.parent_artifact_id, - target_artifact_id: edge.child_artifact_id, - occurrence_id: edge.occurrence_id, - logical_path: edge.logical_path, - evidence_id: evidenceId, - }; - return { - relationship_id: `air_${digestCanonicalValue(semantic, "Artifact inspection")}`, - ...semantic, - }; - }); - const allHypotheses = ( inventory: ArtifactInventoryResult, evidenceId: string, diff --git a/tests/boundary/providers/native/artifactProvider.archiveInventory.test.ts b/tests/boundary/providers/native/artifactProvider.archiveInventory.test.ts index 06fe70527..2da4a98f4 100644 --- a/tests/boundary/providers/native/artifactProvider.archiveInventory.test.ts +++ b/tests/boundary/providers/native/artifactProvider.archiveInventory.test.ts @@ -60,6 +60,15 @@ describe("artifact archive inventory", () => { expect(inspectionEvidence.evidence_links).toEqual( inspection.evidence_links, ); + // The graph is delivered once, in the nested inventory Evidence. + expect( + artifactInventoryResultSchema.parse( + inspection.substeps[0]?.evidence.normalized_result, + ).occurrences, + ).toHaveLength(3); + expect(inspection.observations.map(({ kind }) => kind)).toEqual([ + "root-manifest", + ]); const cancellation = new AbortController(); cancellation.abort(); await expect( From 7296f2b5bfff921b2ca16f942a09616c8adf2b3f Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:13:34 -0700 Subject: [PATCH 176/189] perf(javascript)!: stop repeating the semantic identifier strategy per fact (#1474) Every semantic graph node and relation carried an identifier_strategy object whose schema admits exactly one value per record type. The constant made up about 9% of analyze_javascript_application output (Obsidian app.asar: 12.04 MB to 10.96 MB), and semantic traces repeated it on every returned fact. The node_id and relation_id schema descriptions now state how each identifier is derived. BREAKING CHANGE: Semantic graph nodes and relations no longer include identifier_strategy, and relation IDs no longer hash that constant. Evidence recorded by earlier versions does not validate against the new semantic graph schema. Co-authored-by: Claude Opus 5.5 --- src/domain/javascript/javascriptSemanticGraph.ts | 8 -------- .../javascript/javascriptSemanticGraphSchemas.ts | 16 ++++++---------- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticGraph.ts b/src/domain/javascript/javascriptSemanticGraph.ts index 69b3bb967..9ab2dd485 100644 --- a/src/domain/javascript/javascriptSemanticGraph.ts +++ b/src/domain/javascript/javascriptSemanticGraph.ts @@ -127,10 +127,6 @@ export const createJavaScriptSemanticGraphNode = ( ...parsed, application_node_ids: uniqueSorted(parsed.application_node_ids), evidence: evidenceContexts.intern(parsed.evidence), - identifier_strategy: { - strategy: "semantic-content-sha256" as const, - stability: "artifact-version" as const, - }, }; return javaScriptSemanticNodeSchema.parse({ ...semantic, @@ -147,10 +143,6 @@ export const createJavaScriptSemanticGraphRelation = ( const semantic = { ...parsed, evidence: evidenceContexts.intern(parsed.evidence), - identifier_strategy: { - strategy: "semantic-content-sha256" as const, - stability: "relationship-exact" as const, - }, }; return javaScriptSemanticRelationSchema.parse({ ...semantic, diff --git a/src/domain/javascript/javascriptSemanticGraphSchemas.ts b/src/domain/javascript/javascriptSemanticGraphSchemas.ts index fb03f1a4d..4048ae698 100644 --- a/src/domain/javascript/javascriptSemanticGraphSchemas.ts +++ b/src/domain/javascript/javascriptSemanticGraphSchemas.ts @@ -233,11 +233,9 @@ export const javaScriptSemanticNodeInputSchema = z.strictObject({ export const javaScriptSemanticNodeSchema = javaScriptSemanticNodeInputSchema.extend({ evidence: javaScriptSemanticEvidenceReferenceSchema, - node_id: semanticNodeIdSchema, - identifier_strategy: z.strictObject({ - strategy: z.literal("semantic-content-sha256"), - stability: z.literal("artifact-version"), - }), + node_id: semanticNodeIdSchema.describe( + "SHA-256 of the node kind and identity; stable for one artifact version.", + ), }); /** One directed semantic relationship before its ID is derived. */ @@ -254,11 +252,9 @@ export const javaScriptSemanticRelationInputSchema = z.strictObject({ export const javaScriptSemanticRelationSchema = javaScriptSemanticRelationInputSchema.extend({ evidence: javaScriptSemanticEvidenceReferenceSchema, - relation_id: semanticRelationIdSchema, - identifier_strategy: z.strictObject({ - strategy: z.literal("semantic-content-sha256"), - stability: z.literal("relationship-exact"), - }), + relation_id: semanticRelationIdSchema.describe( + "SHA-256 of the exact relation content, including its evidence reference.", + ), }); /** Reasons semantic analysis can leave an explicit frontier. */ From 1f0775684b2cf8089bddfa7e2f0ee9aa6517c8a8 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:21:16 +0800 Subject: [PATCH 177/189] fix(artifacts): keep case-distinct archive names in inventory (#1480) ZIP member names are case-sensitive. Inventory was folding them with a filesystem case rule, so shrunk APKs never became evidence for the Android application graph. Logical registration now keeps both spellings and records an English Unicode case-folding limitation. Extraction fails only when the destination directory already holds the other spelling. Co-authored-by: Cursor Agent --- docs/android-analysis.md | 9 +- src/artifacts/ArtifactPaths.ts | 168 ++++++++++++++++-- src/artifacts/SafeOutputTree.ts | 35 +++- src/artifacts/inventory/scanCanonical.ts | 23 ++- src/artifacts/inventory/scanReader.ts | 16 +- src/domain/analysisErrorPresentation.ts | 23 ++- src/domain/android/androidApplication.ts | 37 +--- src/domain/zipPackageFormat.ts | 3 +- .../artifactProvider.archiveSafety.test.ts | 70 ++++++-- .../artifactProvider.failureDetail.test.ts | 91 +++++++--- tests/composition/android/application.test.ts | 45 +++++ 11 files changed, 425 insertions(+), 95 deletions(-) diff --git a/docs/android-analysis.md b/docs/android-analysis.md index efcb05c64..849aeb2b1 100644 --- a/docs/android-analysis.md +++ b/docs/android-analysis.md @@ -126,8 +126,13 @@ also stops target hashing before provider admission. These operations do not execute the APK or provide split APK/AAB handling, signature validation, full resource-table semantics, native-library analysis or -Android runtime capture. Existing artifact inventory/extraction tools can supply -archive evidence. Project that Evidence with the execution-free inventory tool: +Android runtime capture. An `.aab` suffix is a ZIP archive, not an APK, so +Android tools and the application graph do not treat it as a standalone APK. +Existing artifact inventory/extraction tools can supply archive evidence. +Inventory keeps ZIP names that differ only in case and records that a +case-insensitive destination cannot store both spellings. Extraction fails +only when that destination directory cannot keep both names. Project that +Evidence with the execution-free inventory tool: ```sh rea project-android-application-graph '{"inventory_evidence":[]}' diff --git a/src/artifacts/ArtifactPaths.ts b/src/artifacts/ArtifactPaths.ts index d5ec35cb4..ce8d6c515 100644 --- a/src/artifacts/ArtifactPaths.ts +++ b/src/artifacts/ArtifactPaths.ts @@ -1,9 +1,24 @@ import { posix } from "node:path"; +import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; import { ArtifactReaderFailure } from "./ArtifactReader.js"; const DRIVE_OR_UNC = /^(?:[A-Za-z]:|\\|\/\/)/u; +/** + * English Unicode case folding used only to describe logical names a + * case-insensitive destination might collapse. It is not a filesystem case table. + */ +const ENGLISH_UNICODE_CASE_NOTE = + "This comparison is not a filesystem observation."; + +/** Inventory limitation when logical names collide under English Unicode case folding. */ +export const ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION = `Logical archive names collide under English (en-US) Unicode case folding; a case-insensitive destination cannot store both spellings. ${ENGLISH_UNICODE_CASE_NOTE}`; + +/** User-facing prefix for a destination that cannot keep two logical spellings. */ +export const DESTINATION_CASE_COLLISION_PREFIX = + "Destination filesystem cannot store both "; + /** Normalize an untrusted logical archive path without touching filesystem. */ export const normalizeArtifactPath = (input: string): string => { if ( @@ -30,7 +45,7 @@ export const normalizeArtifactPath = (input: string): string => { return normalized; }; -/** Reject exact, Unicode-normalized, case-folded, and prefix collisions. */ +/** Reject exact and same-spelling prefix collisions. Case-distinct names stay distinct. */ export class ArtifactPathRegistry { readonly #root: PathTrieNode = { kind: undefined, children: new Map() }; @@ -43,16 +58,10 @@ export class ArtifactPathRegistry { "path", `Artifact prefix conflict: ${path}`, ); - const foldedPart = part.toLocaleLowerCase("en-US"); - let child = node.children.get(foldedPart); - if (child !== undefined && child.spelling !== part) - throw new ArtifactReaderFailure( - "path", - `Artifact path collision: ${path} differs only in case from ${[...parts.slice(0, index), child.spelling].join("/")}`, - ); + let child = node.children.get(part); if (child === undefined) { - child = { spelling: part, kind: undefined, children: new Map() }; - node.children.set(foldedPart, child); + child = { kind: undefined, children: new Map() }; + node.children.set(part, child); } node = child; if (index === parts.length - 1) { @@ -73,7 +82,144 @@ export class ArtifactPathRegistry { } interface PathTrieNode { - readonly spelling?: string; kind: "file" | "directory" | "symlink" | "slice" | undefined; readonly children: Map; } + +interface CaseNode { + readonly bySpelling: Map; + readonly spellingsByFold: Map; + readonly terminals: string[]; +} + +const emptyCaseNode = (): CaseNode => ({ + bySpelling: new Map(), + spellingsByFold: new Map(), + terminals: [], +}); + +const englishCaseFold = (part: string): string => + part.toLocaleLowerCase("en-US"); + +/** + * Record English (en-US) Unicode case collisions on each affected occurrence. + * Returns the inventory limitation when any logical names collide. + */ +export const annotateEnglishUnicodeCaseCollisions = ( + occurrences: readonly { + readonly logical_path: string; + limitations: string[]; + }[], +): string | undefined => { + const collisions = englishUnicodeCaseCollisions( + occurrences.map(({ logical_path }) => logical_path), + ); + if (collisions.size === 0) return undefined; + for (const occurrence of occurrences) { + const others = collisions.get(occurrence.logical_path); + if (others === undefined || others.length === 0) continue; + occurrence.limitations.push( + `Logical path ${occurrence.logical_path} collides under English (en-US) Unicode case folding with ${others.join(", ")}; a case-insensitive destination cannot store both. ${ENGLISH_UNICODE_CASE_NOTE}`, + ); + } + return ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION; +}; + +/** + * Name the directory-listing spelling that differs from the requested segment + * only by English (en-US) Unicode case. Exact matches are the same logical name. + */ +export const destinationCaseCollisionMessage = ( + requestedPath: string, + existingNames: readonly string[], +): string | undefined => { + const slash = requestedPath.lastIndexOf("/"); + const segment = slash < 0 ? requestedPath : requestedPath.slice(slash + 1); + if (existingNames.includes(segment)) return undefined; + const folded = englishCaseFold(segment); + const existing = existingNames + .filter((name) => englishCaseFold(name) === folded) + .sort(compareUnicodeCodePoints)[0]; + if (existing === undefined) return undefined; + const parent = slash < 0 ? "" : requestedPath.slice(0, slash + 1); + return `${DESTINATION_CASE_COLLISION_PREFIX}${requestedPath} and ${parent}${existing}; inventory retains both logical names.`; +}; + +const englishUnicodeCaseCollisions = ( + paths: readonly string[], +): ReadonlyMap => { + const root = emptyCaseNode(); + for (const path of paths) { + if (path.length === 0 || path === ".") continue; + let node = root; + for (const part of path.split("/")) { + const folded = englishCaseFold(part); + const spellings = node.spellingsByFold.get(folded); + if (spellings === undefined) node.spellingsByFold.set(folded, [part]); + else if (!spellings.includes(part)) spellings.push(part); + let child = node.bySpelling.get(part); + if (child === undefined) { + child = emptyCaseNode(); + node.bySpelling.set(part, child); + } + node = child; + } + node.terminals.push(path); + } + const collisions = new Map>(); + recordCaseCollisions(root, collisions); + return new Map( + [...collisions.entries()].map(([path, others]) => [ + path, + [...others].sort(compareUnicodeCodePoints), + ]), + ); +}; + +const recordCaseCollisions = ( + node: CaseNode, + collisions: Map>, +): void => { + for (const spellings of node.spellingsByFold.values()) + if (spellings.length > 1) noteFoldedSpellings(node, spellings, collisions); + for (const child of node.bySpelling.values()) + recordCaseCollisions(child, collisions); +}; + +const noteFoldedSpellings = ( + node: CaseNode, + spellings: readonly string[], + collisions: Map>, +): void => { + const groups = spellings.map((spelling) => { + const child = node.bySpelling.get(spelling); + return child === undefined ? [] : terminalsUnder(child); + }); + for (const [index, group] of groups.entries()) + noteCaseGroup( + group, + groups.flatMap((candidate, candidateIndex) => + candidateIndex === index ? [] : candidate, + ), + collisions, + ); +}; + +const noteCaseGroup = ( + group: readonly string[], + others: readonly string[], + collisions: Map>, +): void => { + for (const path of group) { + const set = collisions.get(path) ?? new Set(); + for (const other of others) if (other !== path) set.add(other); + collisions.set(path, set); + } +}; + +const terminalsUnder = (node: CaseNode): readonly string[] => { + const paths = [...node.terminals]; + for (const child of node.bySpelling.values()) + paths.push(...terminalsUnder(child)); + return paths; +}; diff --git a/src/artifacts/SafeOutputTree.ts b/src/artifacts/SafeOutputTree.ts index fafb6fee4..05ce0ac68 100644 --- a/src/artifacts/SafeOutputTree.ts +++ b/src/artifacts/SafeOutputTree.ts @@ -4,6 +4,7 @@ import { lstat, mkdir, open, + readdir, realpath, rm, type FileHandle, @@ -14,6 +15,7 @@ import { streamChunkToBuffer } from "./StreamBytes.js"; import { ArtifactPathRegistry, + destinationCaseCollisionMessage, normalizeArtifactPath, } from "./ArtifactPaths.js"; import { ArtifactReaderFailure } from "./ArtifactReader.js"; @@ -134,7 +136,8 @@ export class SafeOutputTree { constants.O_WRONLY | constants.O_NOFOLLOW, 0o600, - ).catch((cause: unknown) => { + ).catch(async (cause: unknown) => { + await throwIfDestinationCaseCollision(dirname(destination), path, cause); throw new ArtifactReaderFailure( "path", `Could not exclusively create extraction path: ${path}`, @@ -245,17 +248,28 @@ export class SafeOutputTree { if (fileName === undefined) throw new ArtifactReaderFailure("path", "Invalid extraction path"); let current = this.#outputRoot; + let logicalParent = ""; for (const part of parts) { + const parentDirectory = current; + const logicalPath = + logicalParent.length === 0 ? part : `${logicalParent}/${part}`; current = join(current, part); + let created = true; await mkdir(current, { mode: 0o700 }).catch((cause: unknown) => { if (!isAlreadyExists(cause)) throw cause; + created = false; }); + if (!created) + await throwIfDestinationCaseCollision(parentDirectory, logicalPath); const metadata = await lstat(current); - if (!metadata.isDirectory() || metadata.isSymbolicLink()) + if (!metadata.isDirectory() || metadata.isSymbolicLink()) { + await throwIfDestinationCaseCollision(parentDirectory, logicalPath); throw new ArtifactReaderFailure( "path", `Unsafe extraction parent: ${relativePath}`, ); + } + logicalParent = logicalPath; } return join(current, fileName); } @@ -330,6 +344,23 @@ const isNotFound = (cause: unknown): boolean => const isAlreadyExists = (cause: unknown): boolean => cause instanceof Error && "code" in cause && cause.code === "EEXIST"; +/** Fail when this directory already holds another spelling of the requested segment. */ +const throwIfDestinationCaseCollision = async ( + parentDirectory: string, + logicalPath: string, + cause?: unknown, +): Promise => { + const names = await readdir(parentDirectory).catch(() => undefined); + if (names === undefined) return; + const message = destinationCaseCollisionMessage(logicalPath, names); + if (message === undefined) return; + throw new ArtifactReaderFailure( + "path", + message, + cause === undefined ? undefined : { cause }, + ); +}; + const abortIfNeeded = (signal?: AbortSignal): void => { if (signal?.aborted === true) throw new ArtifactReaderFailure( diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index abd524693..0719e58f4 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -73,12 +73,12 @@ export const scanCanonicalArtifactInventory = async ( try { if (reader instanceof AsarArtifactReader) await reader.prepareContainer(rootDigest?.sha256, options.signal); - const { nodes, occurrences, pendingContradictions } = await scanReader( - reader, - ownedReaders, - options.signal, - integrity, - ); + const { + nodes, + occurrences, + pendingContradictions, + caseCollisionLimitation, + } = await scanReader(reader, ownedReaders, options.signal, integrity); outcome = { kind: "completed", snapshot: await buildInventorySnapshot({ @@ -91,6 +91,7 @@ export const scanCanonicalArtifactInventory = async ( nodes, occurrences, pendingContradictions, + caseCollisionLimitation, }), }; } catch (cause: unknown) { @@ -130,6 +131,7 @@ interface SnapshotBuildInput { readonly nodes: Map; readonly occurrences: MutableOccurrence[]; readonly pendingContradictions: PendingIntegrityContradiction[]; + readonly caseCollisionLimitation: string | undefined; } const buildInventorySnapshot = async ( @@ -202,7 +204,12 @@ const buildInventorySnapshot = async ( edges: orderedEdges, provenance: reader?.provenance() ?? [], integrity_contradictions: integrityContradictions, - limitations: buildLimitations(rootFormat, reader, integrityContradictions), + limitations: buildLimitations( + rootFormat, + reader, + integrityContradictions, + input.caseCollisionLimitation, + ), }; }; @@ -310,8 +317,10 @@ const buildLimitations = ( rootFormat: ArtifactOccurrence["artifact_format"], reader: ArtifactReader | undefined, integrityContradictions: readonly IntegrityContradiction[], + caseCollisionLimitation: string | undefined, ): string[] => [ ...inventoryLimitations(rootFormat, reader), + ...(caseCollisionLimitation === undefined ? [] : [caseCollisionLimitation]), ...(integrityContradictions.length === 0 ? [] : [ diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 1ee691a74..89b1b628e 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -1,6 +1,7 @@ import { isAbsolute } from "node:path"; import { + annotateEnglishUnicodeCaseCollisions, ArtifactPathRegistry, normalizeArtifactPath, } from "../ArtifactPaths.js"; @@ -64,10 +65,16 @@ export const scanReader = async ( readonly nodes: Map; readonly occurrences: MutableOccurrence[]; readonly pendingContradictions: PendingIntegrityContradiction[]; + readonly caseCollisionLimitation: string | undefined; }> => { const { nodes, occurrences, pendingContradictions } = emptyScan(); if (reader === undefined) - return { nodes, occurrences, pendingContradictions }; + return { + nodes, + occurrences, + pendingContradictions, + caseCollisionLimitation: undefined, + }; const context: ScanContext = { reader, signal, @@ -90,7 +97,12 @@ export const scanReader = async ( context.occurrenceByPath, context.expandedContainerIds, )?.occurrence_id ?? null; - return { nodes, occurrences, pendingContradictions }; + return { + nodes, + occurrences, + pendingContradictions, + caseCollisionLimitation: annotateEnglishUnicodeCaseCollisions(occurrences), + }; }; const visitArtifactEntries = async ( diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 7c71a9b5d..b4fe4ad64 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -191,7 +191,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => { const standardMessage = standardErrorMessage(error._tag); if (standardMessage !== undefined) return standardMessage; if (error instanceof ArtifactOperationError) - return artifactMessage(error.operation, error.reason); + return artifactMessage(error.operation, error.reason, error.detail); if (error instanceof EvidenceReferenceError) return error.reason === "missing" ? `Evidence ${error.evidenceId} is not retained in this session. Supply complete inline Evidence, re-run its producer, or import its bundle before using this reference.` @@ -329,13 +329,13 @@ const START_FAILURE_TAGS: ReadonlySet = new Set([ const artifactMessage = ( operation: ArtifactOperationError["operation"], reason: ArtifactOperationError["reason"], + detail?: string, ): string => { if (reason === "cancelled") return "Artifact operation was cancelled. Start it again when ready."; if (reason === "limit") return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact."; - if (reason === "path") - return "Artifact contains an unsafe or conflicting internal path. Inspect the reported path and correct the artifact before retrying."; + if (reason === "path") return artifactPathMessage(detail); if (reason === "unavailable") return "Artifact processing is unavailable for the current target or host. Check artifact support and required tools."; if (reason === "integrity" && operation === "analyze_javascript_application") @@ -345,6 +345,23 @@ const artifactMessage = ( return "Artifact could not be read or written. Check file access and try again."; }; +const artifactPathMessage = (detail: string | undefined): string => { + // Kept in step with DESTINATION_CASE_COLLISION_PREFIX. Domain does not import + // the artifact adapter that produces the detail. + if ( + detail !== undefined && + detail.startsWith("Destination filesystem cannot store both ") + ) + return detail; + if ( + detail !== undefined && + (detail.startsWith("Artifact path is absolute or unsafe:") || + detail.startsWith("Artifact path is not normalized:")) + ) + return "Artifact contains an unsafe internal path. Inspect the reported path and correct the artifact before retrying."; + return "Artifact contains a conflicting internal path. Inspect the reported path before retrying."; +}; + const evidenceFileMessage = ({ operation, reason, diff --git a/src/domain/android/androidApplication.ts b/src/domain/android/androidApplication.ts index 745b8e0c4..674425749 100644 --- a/src/domain/android/androidApplication.ts +++ b/src/domain/android/androidApplication.ts @@ -125,6 +125,8 @@ export const projectAndroidApplication = ( "Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.", "Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.", "Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.", + "A bridge basis is inferred from the native path and is repeated for every managed component.", + "ZIP inventory cannot see the APK Signing Block, so an empty signing array does not mean the APK is unsigned.", ...(bridgeProjection.coverage.status === "partial" ? [ `Bridge candidate pairs exceeded the projection safety budget; ${bridgeProjection.coverage.omitted_candidates} hypotheses are omitted. Component arrays still include every component from the supplied inventory pages.`, @@ -157,23 +159,12 @@ export const projectAndroidApplication = ( }; const classify = (all: readonly Component[]) => ({ - manifests: all.filter( - ({ path, format }) => - format === "android-manifest" || - /(?:^|\/)AndroidManifest\.xml$/u.test(path), - ), - resources: all.filter( - ({ path, format }) => - format === "android-resources" || /(?:^|\/)resources\.arsc$/u.test(path), - ), - dex: all.filter( - ({ path, format }) => - format === "dex" || /(?:^|\/)[^/]+\.dex$/iu.test(path), - ), - jvm_classes: all.filter( - ({ path, format }) => - format === "jvm-class" || /(?:^|\/)[^/]+\.class$/iu.test(path), + manifests: all.filter(({ path }) => + /(?:^|\/)AndroidManifest\.xml$/u.test(path), ), + resources: all.filter(({ path }) => /(?:^|\/)resources\.arsc$/u.test(path)), + dex: all.filter(({ path }) => /(?:^|\/)[^/]+\.dex$/iu.test(path)), + jvm_classes: all.filter(({ path }) => /(?:^|\/)[^/]+\.class$/iu.test(path)), native_libraries: all.filter( ({ path, format }) => format === "elf" || /(?:^|\/)lib\/[^/]+\/[^/]+\.so$/iu.test(path), @@ -189,19 +180,9 @@ const runtimeFamilies = (all: readonly Component[]) => { const families = new Set< AndroidApplicationProjectionResult["runtime_families"][number] >(); - if ( - all.some( - ({ path, format }) => - format === "dex" || path.toLowerCase().endsWith(".dex"), - ) - ) + if (all.some(({ path }) => path.toLowerCase().endsWith(".dex"))) families.add("dalvik-art"); - if ( - all.some( - ({ path, format }) => - format === "jvm-class" || path.toLowerCase().endsWith(".class"), - ) - ) + if (all.some(({ path }) => path.toLowerCase().endsWith(".class"))) families.add("java-kotlin"); if (all.some(({ format }) => format === "elf")) families.add("native"); if (all.some(({ format }) => format === "javascript-bundle")) diff --git a/src/domain/zipPackageFormat.ts b/src/domain/zipPackageFormat.ts index c45109135..39a8f86a5 100644 --- a/src/domain/zipPackageFormat.ts +++ b/src/domain/zipPackageFormat.ts @@ -22,7 +22,8 @@ export const zipPackageFormatForPath = ( const lower = path.toLowerCase(); if (lower.endsWith(".zip")) return "zip"; if (lower.endsWith(".ipa")) return "ipa"; - if (lower.endsWith(".apk") || lower.endsWith(".aab")) return "apk"; + // An Android App Bundle is a ZIP archive, not a standalone APK. + if (lower.endsWith(".apk")) return "apk"; if (lower.endsWith(".msix") || lower.endsWith(".msixbundle")) return "msix"; if (lower.endsWith(".appx") || lower.endsWith(".appxbundle")) return "appx"; return undefined; diff --git a/tests/boundary/providers/native/artifactProvider.archiveSafety.test.ts b/tests/boundary/providers/native/artifactProvider.archiveSafety.test.ts index 368d029dc..92f88aa9d 100644 --- a/tests/boundary/providers/native/artifactProvider.archiveSafety.test.ts +++ b/tests/boundary/providers/native/artifactProvider.archiveSafety.test.ts @@ -9,6 +9,8 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js"; import { ArtifactPathRegistry, + destinationCaseCollisionMessage, + ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION, normalizeArtifactPath, } from "../../../../src/artifacts/ArtifactPaths.js"; import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js"; @@ -95,17 +97,8 @@ describe("artifact archive safety", () => { }); const registry = new ArtifactPathRegistry(); registry.add("A.js", "file"); - let collisionError: unknown; - try { - registry.add("a.js", "file"); - } catch (error: unknown) { - collisionError = error; - } - expect(collisionError).toBeInstanceOf(ArtifactReaderFailure); - expect(collisionError).toMatchObject({ - reason: "path", - message: "Artifact path collision: a.js differs only in case from A.js", - }); + expect(() => registry.add("a.js", "file")).not.toThrow(); + expect(() => registry.add("A.js", "file")).toThrow(ArtifactReaderFailure); for (const [filePath, childPath] of [ ["Foo", "foo/bar"], @@ -113,11 +106,15 @@ describe("artifact archive safety", () => { ] as const) { const casePrefixRegistry = new ArtifactPathRegistry(); casePrefixRegistry.add(filePath, "file"); - expect(() => casePrefixRegistry.add(childPath, "file")).toThrow( - ArtifactReaderFailure, - ); + expect(() => casePrefixRegistry.add(childPath, "file")).not.toThrow(); } + const exactPrefixRegistry = new ArtifactPathRegistry(); + exactPrefixRegistry.add("Foo", "file"); + expect(() => exactPrefixRegistry.add("Foo/bar", "file")).toThrow( + ArtifactReaderFailure, + ); + const sameDirectoryRegistry = new ArtifactPathRegistry(); sameDirectoryRegistry.add("Foo/one.js", "file"); expect(() => sameDirectoryRegistry.add("Foo/two.js", "file")).not.toThrow(); @@ -126,7 +123,50 @@ describe("artifact archive safety", () => { caseVariantDirectoryRegistry.add("Foo/one.js", "file"); expect(() => caseVariantDirectoryRegistry.add("foo/two.js", "file"), - ).toThrow(ArtifactReaderFailure); + ).not.toThrow(); + }); + + it("names a destination case collision from the directory listing", () => { + expect( + destinationCaseCollisionMessage("res/2f.xml", ["2F.xml", "other.xml"]), + ).toBe( + "Destination filesystem cannot store both res/2f.xml and res/2F.xml; inventory retains both logical names.", + ); + expect( + destinationCaseCollisionMessage("res/2f.xml", ["2f.xml", "2F.xml"]), + ).toBeUndefined(); + }); + + it("extracts logical names that differ only in case", async () => { + const root = await createTestTempDirectory("rea-case-distinct-zip-"); + const path = join(root, "fixture.zip"); + const writer = new ZipWriter(new Uint8ArrayWriter()); + await writer.add("Main.js", new TextReader("upper")); + await writer.add("main.js", new TextReader("lower")); + await writeFile(path, await writer.close()); + const parsed = await parseBinaryTarget(path); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + const result = await inventory(parsed.value); + expect(result.limitations).toContain( + ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION, + ); + expect( + result.occurrences + .filter(({ logical_path }) => logical_path !== ".") + .map(({ logical_path }) => logical_path) + .sort(), + ).toEqual(["Main.js", "main.js"]); + const output = join(root, "output"); + const extracted = await new ArtifactProvider(process.env) + .createClient(parsed.value) + .execute( + "extract_artifact", + artifactExtractionExecutionSchema.parse({ output_root: output }), + ); + expect(extracted.ok).toBe(true); + expect(await readFile(join(output, "Main.js"), "utf8")).toBe("upper"); + expect(await readFile(join(output, "main.js"), "utf8")).toBe("lower"); }); }); const inventory = async (targetValue: BinaryTarget) => { diff --git a/tests/boundary/providers/native/artifactProvider.failureDetail.test.ts b/tests/boundary/providers/native/artifactProvider.failureDetail.test.ts index dcec03c93..e2b2fd385 100644 --- a/tests/boundary/providers/native/artifactProvider.failureDetail.test.ts +++ b/tests/boundary/providers/native/artifactProvider.failureDetail.test.ts @@ -6,30 +6,73 @@ import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js"; +import { + destinationCaseCollisionMessage, + ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION, +} from "../../../../src/artifacts/ArtifactPaths.js"; import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js"; +import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js"; +import { ArtifactOperationError } from "../../../../src/domain/artifactOperationError.js"; import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; -it.each([ - [ - ["Main.js", "main.js"], - "Artifact path collision: main.js differs only in case from Main.js", - ], - [["a\\b.js"], 'Artifact path is absolute or unsafe: "a\\\\b.js"'], -] as const)( - "reports the failed path constraint for %j", - async (entries, detail) => { - const root = await createTestTempDirectory("rea-artifact-detail-"); - const path = join(root, "fixture.zip"); - await writeOrderedZip(path, entries); - const target = await parseBinaryTarget(path); - if (!target.ok) throw new Error("expected a ZIP target"); - const result = await new ArtifactProvider(process.env) - .createClient(target.value) - .execute("inventory_artifact", {}); - if (result.ok) throw new Error("expected the path constraint to fail"); - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "artifact_operation_failed", - details: { operation: "inventory_artifact", reason: "path", detail }, - }); - }, -); +it("keeps logical names that differ only in case and records the limitation", async () => { + const root = await createTestTempDirectory("rea-artifact-detail-"); + const path = join(root, "fixture.zip"); + await writeOrderedZip(path, ["Main.js", "main.js"]); + const target = await parseBinaryTarget(path); + if (!target.ok) throw new Error("expected a ZIP target"); + const result = await new ArtifactProvider(process.env) + .createClient(target.value) + .execute("inventory_artifact", {}); + if (!result.ok) throw result.error; + const inventory = artifactInventoryResultSchema.parse(result.value.result); + expect(inventory.occurrences.map(({ logical_path }) => logical_path)).toEqual( + expect.arrayContaining(["Main.js", "main.js"]), + ); + expect(inventory.limitations).toContain( + ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION, + ); + for (const logicalPath of ["Main.js", "main.js"]) { + expect( + inventory.occurrences + .find((occurrence) => occurrence.logical_path === logicalPath) + ?.limitations.join("\n"), + ).toContain("English (en-US) Unicode case folding"); + } +}); + +it("reports an unsafe path as a hostile artifact path", async () => { + const root = await createTestTempDirectory("rea-artifact-detail-"); + const path = join(root, "fixture.zip"); + await writeOrderedZip(path, ["a\\b.js"]); + const target = await parseBinaryTarget(path); + if (!target.ok) throw new Error("expected a ZIP target"); + const result = await new ArtifactProvider(process.env) + .createClient(target.value) + .execute("inventory_artifact", {}); + if (result.ok) throw new Error("expected the path constraint to fail"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "artifact_operation_failed", + message: + "Artifact contains an unsafe internal path. Inspect the reported path and correct the artifact before retrying.", + details: { + operation: "inventory_artifact", + reason: "path", + detail: 'Artifact path is absolute or unsafe: "a\\\\b.js"', + }, + }); +}); + +it("returns a destination case collision as the user-facing path message", () => { + const detail = destinationCaseCollisionMessage("res/2f.xml", ["2F.xml"]); + expect(detail).toEqual(expect.any(String)); + if (detail === undefined) return; + expect( + projectAnalysisError( + new ArtifactOperationError("extract_artifact", "path", undefined, detail), + ), + ).toMatchObject({ + message: detail, + details: { reason: "path", detail }, + }); +}); diff --git a/tests/composition/android/application.test.ts b/tests/composition/android/application.test.ts index 082a706b0..3529dc4e8 100644 --- a/tests/composition/android/application.test.ts +++ b/tests/composition/android/application.test.ts @@ -86,6 +86,12 @@ describe("Android application projection", () => { expect(left.bridge_candidates).toEqual([ expect.objectContaining({ basis: "react-native-convention" }), ]); + expect(left.limitations).toEqual( + expect.arrayContaining([ + "A bridge basis is inferred from the native path and is repeated for every managed component.", + "ZIP inventory cannot see the APK Signing Block, so an empty signing array does not mean the APK is unsigned.", + ]), + ); expect(JSON.stringify(left)).not.toContain("opaque signing"); }); @@ -146,6 +152,45 @@ describe("Android application projection", () => { }); }); +describe("case-distinct APK resource names", () => { + it("inventories and projects an APK whose resource names differ only in case", async () => { + const root = await createTestTempDirectory("rea-android-case-"); + const path = join(root, "Shrunk.apk"); + const writer = new ZipWriter(new Uint8ArrayWriter()); + await writer.add( + "AndroidManifest.xml", + new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0])), + ); + await writer.add( + "classes.dex", + new Uint8ArrayReader( + Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]), + ), + ); + await writer.add("res/2F.xml", new TextReader("upper")); + await writer.add("res/2f.xml", new TextReader("lower")); + await writeFile(path, await writer.close()); + + const inventory = parseEvidence( + await runProviderAnalysis(path, "inventory_artifact", {}), + ); + const result = projectAndroidApplicationEvidence({ + inventory_evidence: [inventory], + }); + const projection = androidApplicationProjectionResultSchema.parse( + requireSuccessfulProjection(result).normalized_result, + ); + expect(projection.root_format).toBe("apk"); + expect(projection.components.manifests).toHaveLength(1); + expect(projection.components.dex).toHaveLength(1); + expect(JSON.stringify(inventory)).toContain("res/2F.xml"); + expect(JSON.stringify(inventory)).toContain("res/2f.xml"); + expect(JSON.stringify(inventory)).toContain( + "English (en-US) Unicode case folding", + ); + }); +}); + describe("Android bridge candidate coverage", () => { it("returns every component and bridge candidate from the inventory", async () => { const root = await createTestTempDirectory("rea-android-complete-"); From b09d02d93cbadfa0ced21e7c489c7d47fb317228 Mon Sep 17 00:00:00 2001 From: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:55:18 +0800 Subject: [PATCH 178/189] feat(website): add a blog for methods and project notes --- website/public/blog/index.html | 154 ++++++++++++++++++ website/public/examples/dino-lab/index.html | 3 +- website/public/faq/index.html | 1 + website/public/first-investigation/index.html | 3 +- website/public/get-started/index.html | 3 +- website/public/guides/browser/index.html | 3 +- website/public/guides/index.html | 3 +- website/public/guides/javascript/index.html | 3 +- website/public/guides/native/index.html | 3 +- website/public/index.html | 1 + website/public/showcase/aegis/index.html | 1 + website/public/showcase/ctf/index.html | 1 + website/public/showcase/dx-ball/index.html | 1 + website/public/showcase/index.html | 1 + website/public/showcase/notion/index.html | 1 + website/public/showcase/th04/index.html | 1 + 16 files changed, 176 insertions(+), 7 deletions(-) create mode 100644 website/public/blog/index.html diff --git a/website/public/blog/index.html b/website/public/blog/index.html new file mode 100644 index 000000000..eec6da2a6 --- /dev/null +++ b/website/public/blog/index.html @@ -0,0 +1,154 @@ + + + + + + Reverse Engineering Methods and Project Notes — REA + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + +

    Methods and project notes.

    +

    + How we approach reverse engineering, game reconstruction, ports and + mods. +

    +
    +
    +
    +

    Game reconstruction
    Article outline

    +
    +

    Reconstructing Touhou with AI agents

    +

    + A repeatable workflow, illustrated by TH08, TH095 and TH04: build + on existing work, carry lessons into a new game, and adapt the + method to an older platform. +

    +

    By N0zoM1z0 · Outline in progress

    +
    +
    +
    +
    + +

    + + Top + + + diff --git a/website/public/examples/dino-lab/index.html b/website/public/examples/dino-lab/index.html index d0bc84c76..02452bda9 100644 --- a/website/public/examples/dino-lab/index.html +++ b/website/public/examples/dino-lab/index.html @@ -63,7 +63,8 @@ >Reverse Engineer Anything diff --git a/website/public/faq/index.html b/website/public/faq/index.html index fa4a64a83..3ab51b9d3 100644 --- a/website/public/faq/index.html +++ b/website/public/faq/index.html @@ -63,6 +63,7 @@ >