chore: merge main into Windows DLL support branch

This commit is contained in:
morluto
2026-10-10 13:42:54 +08:00
737 changed files with 29506 additions and 11793 deletions
@@ -11,6 +11,30 @@ export async function startBrowserVerifierSite() {
response.destroy();
return;
}
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(`<!doctype html><html><body data-run="${run}"><pre id="environment"></pre>
<button id="refresh-environment">Refresh environment</button><script>
const refresh = () => document.querySelector('#environment').textContent = JSON.stringify({
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
locale: Intl.DateTimeFormat().resolvedOptions().locale,
dpr: devicePixelRatio, width: innerWidth, height: innerHeight
});
document.querySelector('#refresh-environment').onclick = refresh;
window.releaseScenario = () => {
const release = document.createElement('span');
release.id = 'release-' + document.body.dataset.run;
document.body.append(release);
};
refresh();
</script></body></html>`);
return;
}
if (request.url === "/slow-json") {
response.setHeader("content-type", "application/json");
response.write('{"pending":');
@@ -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: [],
});
+14 -5
View File
@@ -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 { 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(
@@ -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 = PRODUCT_IDENTITY.packageSpecifier;
const pinnedSpecifier = PRODUCT_IDENTITY.registrationPackageSpecifier;
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 });
@@ -0,0 +1,364 @@
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 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, values, run }) =>
browserScenarioSchema.parse({
browser: { mode: "connect", cdp_endpoint: endpoint, target_id: targetId },
start_url: {
url: `${origin}/scenario-environment${run === undefined ? "" : `?run=${run}`}`,
},
environment: {
locale: values.locale,
timezone: values.timezone,
viewport: {
width: values.width,
height: values.height,
device_scale_factor: values.dpr,
},
},
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, 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 id="environment">([^<]+)<\/pre>/u.exec(text);
assert.ok(observed, "DOM omitted the page's actual environment values");
assert.deepEqual(JSON.parse(observed[1]), values);
}
};
/** 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,
values: expected,
});
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);
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 },
{ toolDefinition: definition },
),
"capture_browser_scenario",
),
);
await verifyConcurrentMcpCapture({
client,
definition,
connection,
endpoint,
targetId,
origin,
readEnvironment,
assertRestored,
});
} 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();
}
}
const verifyConcurrentMcpCapture = async ({
client,
definition,
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, toolDefinition: definition },
);
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,
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",
);
}
+12 -3
View File
@@ -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",
),
)
)
+12
View File
@@ -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[];
@@ -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);
-19
View File
@@ -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<ProductCatalog>;
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<string>;
+2 -15
View File
@@ -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),
},
},
};
+39 -6
View File
@@ -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,19 +74,46 @@ 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],
);
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(
@@ -88,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",
+25 -3
View File
@@ -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(
-29
View File
@@ -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: [],
};
};
+1 -1
View File
@@ -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;
}
+2 -2
View File
@@ -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:");
+4
View File
@@ -81,6 +81,10 @@ export async function verifyPackageEnvironment({
COPILOT_HOME: join(home, ".copilot"),
GROK_HOME: join(home, ".grok"),
SAND_DATA_ROOT: join(home, ".grokbot"),
OMP_PROFILE: undefined,
PI_CODING_AGENT_DIR: undefined,
PI_CONFIG_DIR: undefined,
PI_PROFILE: undefined,
OPENCODE_CONFIG: undefined,
XDG_CONFIG_HOME: join(home, ".config"),
PATH: `${fakeBin}:${process.env.PATH ?? ""}`,
+2 -1
View File
@@ -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/managed/function-dossier.mjs";
import { json, run } from "./lib/verify-package-core.mjs";
const buildManagedFixtures = async (workspace) => {
const managedPath = join(workspace, "managed-fixture.exe");
+4
View File
@@ -103,6 +103,10 @@ export async function verifyPackageUpdate({
COPILOT_HOME: join(home, ".copilot"),
GROK_HOME: join(home, ".grok"),
SAND_DATA_ROOT: join(home, ".grokbot"),
OMP_PROFILE: undefined,
PI_CODING_AGENT_DIR: undefined,
PI_CONFIG_DIR: undefined,
PI_PROFILE: undefined,
XDG_CONFIG_HOME: join(home, ".config"),
OPENCODE_CONFIG: join(home, ".config", "opencode", "opencode.json"),
npm_config_prefix: prefix,
+4
View File
@@ -106,6 +106,10 @@ async function verifyPublishedUpdate({ version: targetVersion, canaryRoot }) {
COPILOT_HOME: join(home, ".copilot"),
GROK_HOME: join(home, ".grok"),
SAND_DATA_ROOT: join(home, ".grokbot"),
OMP_PROFILE: undefined,
PI_CODING_AGENT_DIR: undefined,
PI_CONFIG_DIR: undefined,
PI_PROFILE: undefined,
XDG_CONFIG_HOME: join(home, ".config"),
OPENCODE_CONFIG: join(home, ".config", "opencode", "opencode.json"),
npm_config_cache: join(canaryRoot, "update-cache"),
+7
View File
@@ -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 {
+22 -8
View File
@@ -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,
+31 -12
View File
@@ -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)
+4
View File
@@ -115,6 +115,10 @@ try {
COPILOT_HOME: join(home, ".copilot"),
GROK_HOME: join(home, ".grok"),
SAND_DATA_ROOT: join(home, ".grokbot"),
OMP_PROFILE: undefined,
PI_CODING_AGENT_DIR: undefined,
PI_CONFIG_DIR: undefined,
PI_PROFILE: undefined,
};
await mkdir(join(home, ".config", "opencode"), { recursive: true });
await writeFile(
+50
View File
@@ -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,
+20 -1
View File
@@ -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",
+142
View File
@@ -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 });
}
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { chmod, readFile, stat } from "node:fs/promises";
import { relative, sep } from "node:path";
import { parseArtifactInventoryEvidence } from "../../../dist/domain/artifactInventoryEvidence.js";
import {
artifactCliEvidence,
withArtifactMcp,
} from "../../lib/artifact-e2e.mjs";
/** Verify native file roles and permissions on the real compiled bundle fixture. */
export async function verifyMachOOccurrences(app, executable) {
const originalMode = (await stat(executable)).mode & 0o7777;
const originalBytes = await readFile(executable);
const logicalPath = relative(app, executable).split(sep).join("/");
const observations = [];
try {
for (const mode of [0o755, 0o644]) {
await chmod(executable, mode);
const directEvidence = await artifactCliEvidence(
"inspect-artifact",
executable,
);
const direct = parseArtifactInventoryEvidence(directEvidence).inventory;
const containedEvidence = await artifactCliEvidence(
"inspect-artifact",
app,
);
const contained =
parseArtifactInventoryEvidence(containedEvidence).inventory;
assert.equal(direct.complete, true);
assert.equal(contained.complete, true);
const root = direct.occurrences.find(
({ logical_path }) => logical_path === ".",
);
const nested = contained.occurrences.find(
({ logical_path }) => logical_path === logicalPath,
);
assert.ok(root);
assert.ok(nested);
assert.ok(["mach-o", "mach-o-universal"].includes(root.artifact_format));
for (const occurrence of [root, nested]) {
assert.equal(occurrence.artifact_kind, "executable");
assert.equal(occurrence.artifact_format, direct.manifest.root_format);
assert.equal(occurrence.executable, mode === 0o755);
}
assert.equal(root.artifact_id, nested.artifact_id);
assert.equal(root.artifact_id, direct.manifest.root_artifact_id);
const node = contained.nodes.find(
({ artifact_id }) => artifact_id === nested.artifact_id,
);
assert.ok(node);
assert.equal(node.sha256, direct.manifest.root_sha256);
assert.equal(node.format, root.artifact_format);
await withArtifactMcp(app, async (client) => {
const reply = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
assert.notEqual(reply.isError, true, JSON.stringify(reply));
assert.deepEqual(
parseArtifactInventoryEvidence(reply.structuredContent).inventory,
contained,
);
});
observations.push({
mode: mode.toString(8),
artifact_id: root.artifact_id,
artifact_kind: root.artifact_kind,
artifact_format: root.artifact_format,
executable: root.executable,
contained_cli_mcp_parity: true,
});
}
assert.equal(observations[0].artifact_id, observations[1].artifact_id);
assert.deepEqual(await readFile(executable), originalBytes);
return {
direct_cli: true,
contained_cli_mcp: true,
bytes_unchanged: true,
observations,
};
} finally {
await chmod(executable, originalMode);
}
}
+7 -1
View File
@@ -16,6 +16,8 @@ import {
} from "../../fixtures/apple/macos-bundle.mjs";
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);
@@ -67,7 +69,9 @@ const EXPECTED_BUNDLES = [
let report;
try {
const { app } = await buildMacosBundleFixture(root);
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]);
const staging = join(root, "dmg-source");
@@ -164,6 +168,8 @@ 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,
};
@@ -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,
};
}
+137
View File
@@ -0,0 +1,137 @@
import assert from "node:assert/strict";
import { readFile, readdir } from "node:fs/promises";
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
// 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 = fileURLToPath(new URL("../../", import.meta.url));
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: relative(root, path).split(sep).join("/"),
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.`);
+2 -2
View File
@@ -4,7 +4,7 @@ import assert from "node:assert/strict";
import { constants } from "node:buffer";
import { createHash } from "node:crypto";
import { canonicalDigest } from "../../../dist/domain/comparisonSemantics.js";
import { digestCanonicalValue } from "../../../dist/domain/canonicalDigest.js";
import {
createEvidence,
parseEvidence,
@@ -23,7 +23,7 @@ for (let index = 0; index < count; index += 1) {
expected.update(encodedLeaf);
}
expected.update("]}");
assert.equal(canonicalDigest(value), expected.digest("hex"));
assert.equal(digestCanonicalValue(value), expected.digest("hex"));
const evidence = createEvidence(
undefined,
+3 -3
View File
@@ -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) {
-28
View File
@@ -50,31 +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",
},
signature: null,
locals: [],
},
pseudocode: "",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
limitations: [],
};
}
+1 -1
View File
@@ -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/managed/function-dossier.mjs";
import {
alternateMvid,
buildNativePeFixture,
@@ -21,7 +22,6 @@ import { createManagedConformanceSupport } from "./support.mjs";
import {
comparisonLimits,
defaultIlBody,
functionDossier,
inspectionLimits,
memberLimits,
nativeBoundaryLimits,
+1 -1
View File
@@ -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(