fix(process): stabilize native capture and ownership prerequisites

This commit is contained in:
morluto
2026-10-09 06:49:02 +08:00
parent 44fd18305f
commit 2b27515476
11 changed files with 341 additions and 114 deletions
+18
View File
@@ -160,6 +160,24 @@ try {
if (mode === "mcp") assert.deepEqual(value.result, report);
return report;
};
const ownershipProbe = join(root.path, "ownership-prerequisite.hex");
await writeFile(ownershipProbe, "0x00");
const missingInspection = await inspect(
"cli",
ownershipProbe,
"hex",
"unsupported_provider",
{
command: process.execPath,
prefix: [],
client,
environment: { ...environment, PATH: root.path },
},
);
assert.equal(missingInspection.code, "capability_unavailable");
assert.match(missingInspection.message, /procps-compatible ps/u);
assert.equal(missingInspection.details.operation, "prepare_owned_process");
cases++;
for (const [name, optimizer, viaIR] of [
["plain", false, false],
["optimized", true, false],
+65 -11
View File
@@ -28,13 +28,6 @@ for (const tool of ["clang", "lldb", "codesign", "nm"])
);
}
const developerMode = await exec("/usr/sbin/DevToolsSecurity", ["-status"]);
if (
!/enabled/iu.test(developerMode.stdout) ||
/disabled/iu.test(developerMode.stdout)
)
throw new Error(
"Native call observation verification requires macOS Developer Mode; DevToolsSecurity reports it disabled.",
);
const SOURCE = fileURLToPath(
new URL("../tests/conformance/native/calls.m", import.meta.url),
@@ -51,6 +44,8 @@ const INPUT = {
{ kind: "function", name: "rea_call_add" },
],
environment: { REA_CALLS_MARKER: "observed" },
// Entry stops and Objective-C runtime reads slow the real target on busy hosts.
duration_ms: 30_000,
argument_registers: 4,
backtrace_frames: 1,
};
@@ -59,6 +54,7 @@ const CLI_TIMEOUT_MS = 180_000;
/** Pointer-free facts that two runs of the same scenario must share. */
const stable = (result) =>
result.events.map((event) => ({
breakpoint_index: event.breakpoint_index,
symbol: event.symbol,
file_address: event.file_address,
selector: event.selector,
@@ -159,8 +155,7 @@ const checkBounds = async (binary) => {
binary,
[
JSON.stringify({
breakpoints: [{ kind: "function", name: "nanosleep" }],
arguments: ["--wait"],
breakpoints: [{ kind: "function", name: "rea_call_add" }],
max_events: 2,
duration_ms: 30_000,
}),
@@ -189,8 +184,9 @@ const checkBounds = async (binary) => {
};
const cliFailure = async (binary) => {
let output;
try {
await exec(
const completed = await exec(
process.execPath,
[
fileURLToPath(new URL("rea.mjs", import.meta.url)),
@@ -204,10 +200,11 @@ const cliFailure = async (binary) => {
timeout: CLI_TIMEOUT_MS,
},
);
output = completed.stdout;
} catch (cause) {
return JSON.parse(cause.stdout);
}
throw new Error("observe-native-calls unexpectedly succeeded");
throw new Error(`observe-native-calls unexpectedly succeeded: ${output}`);
};
/** Hardened runtime blocks the debugger unless get-task-allow is granted. */
@@ -226,6 +223,22 @@ const checkHardenedRuntime = async (directory, binary) => {
const denied = await cliFailure(blocked);
assert.equal(denied.code, "capability_unavailable");
assert.match(denied.details.reason, /^debugger-attach-denied: /u);
await withArtifactMcp(blocked, async (client) => {
const deniedMcp = await client.callTool(
{
name: "observe_native_calls",
arguments: INPUT,
},
{ timeout: CLI_TIMEOUT_MS },
);
assert.equal(deniedMcp.isError, true, JSON.stringify(deniedMcp));
assert.equal(deniedMcp.structuredContent.error.code, denied.code);
assert.match(
deniedMcp.structuredContent.error.details.reason,
/^debugger-attach-denied: /u,
);
assert.ok(deniedMcp.structuredContent.error.details.partial_observation);
});
const allowed = join(directory, "debuggable");
const entitlements = join(directory, "get-task-allow.plist");
await writeFile(
@@ -267,14 +280,55 @@ try {
"observe_native_calls",
INPUT,
);
assert.equal(
viaMcp.process.outcome,
"exited",
JSON.stringify(viaMcp.coverage),
);
assert.deepEqual(stable(viaMcp), stable(viaCli));
assert.equal(viaMcp.process.stdout.text, viaCli.process.stdout.text);
// Two caller selections may resolve to one address. Each must retain its
// own hit; consuming only the first stop-reason ID loses the second.
const overlapping = {
breakpoints: [
{ kind: "function", name: "rea_call_add" },
{ kind: "function", name: "rea_call_add", module: basename(binary) },
],
duration_ms: 30_000,
argument_registers: 2,
};
const paired = await artifactMcpResult(
client,
"observe_native_calls",
overlapping,
);
assert.equal(paired.process.outcome, "exited");
assert.equal(paired.events.length, 6);
for (const index of [0, 1]) {
const hits = paired.events.filter(
(event) => event.breakpoint_index === index,
);
assert.deepEqual(
hits.map((event) => event.registers[0].value),
["0x0", "0x1", "0x2"],
);
assert.ok(hits.every((event) => event.symbol === "rea_call_add"));
}
const capped = await artifactMcpResult(client, "observe_native_calls", {
...overlapping,
max_events: 2,
});
assert.equal(capped.process.outcome, "event-limit");
assert.equal(capped.events.length, 2);
assert.equal(capped.process.terminated, true);
});
await checkBounds(binary);
await checkHardenedRuntime(directory, binary);
console.log(
JSON.stringify({
ok: true,
developer_mode: developerMode.stdout.trim(),
mocked: false,
cli: true,
stdio_mcp: true,
+63 -7
View File
@@ -1,4 +1,5 @@
import { execFile, spawn } from "node:child_process";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -7,6 +8,8 @@ import { promisify } from "node:util";
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
import { observeNativeUi } from "../dist/native/NativeUiObservation.js";
import { NATIVE_UI_HELPER_MAX_BUFFER } from "../dist/native/NativeUiOutputBudget.js";
import { artifactMcpResult, withArtifactMcp } from "./lib/artifact-e2e.mjs";
import { observeProcessStartIdentity } from "../dist/process/ProcessOwnershipObservation.js";
if (process.platform !== "darwin")
throw new Error(
@@ -14,7 +17,9 @@ if (process.platform !== "darwin")
);
const root = await mkdtemp(join(tmpdir(), "rea-ui-fixture-"));
let child;
let childExit;
let fixturePid;
let fixtureIdentity;
let report;
try {
const childRetrievalTest = join(root, "child-retrieval-test");
@@ -89,6 +94,7 @@ try {
["-W", "-n", "-g", "--stdout", coordinates, join(root, "Fixture.app")],
{ stdio: "ignore" },
);
childExit = new Promise((resolve) => child.once("exit", resolve));
let scope;
const deadline = Date.now() + 20000;
while (Date.now() < deadline) {
@@ -104,6 +110,12 @@ try {
"Source-owned UI fixture failed to expose one window within 20 seconds",
);
fixturePid = scope.pid;
fixtureIdentity = await observeProcessStartIdentity(fixturePid);
assert.equal(
fixtureIdentity?.state,
"readable",
"Fixture OS start identity is unavailable",
);
const target = await parseBinaryTarget(executable);
if (!target.ok) throw target.error;
const observation = await observeNativeUi(target.value, "observe_native_ui", {
@@ -180,6 +192,43 @@ try {
`Native UI CLI did not preserve the selected scenario: ${JSON.stringify(evidence.error ?? evidence.normalized_result?.steps?.map(({ outcome, reason }) => ({ outcome, reason })))}`,
);
scenarioStatus = "selected-AX-button-action-and-CLI-parity-observed";
await withArtifactMcp(executable, async (client) => {
const observed = await artifactMcpResult(client, "observe_native_ui", {
...scope,
screenshot: false,
});
if (
!observed.initial.nodes.some(
(node) =>
node.role === "AXButton" &&
JSON.stringify(node.path) === JSON.stringify(button.path),
)
)
throw new Error("MCP omitted the selected fixture's actual AX button");
const captured = await artifactMcpResult(
client,
"capture_native_ui_scenario",
{
...scope,
screenshot: false,
steps: [
{ kind: "click", path: button.path },
{ kind: "wait", milliseconds: 200 },
],
},
);
if (
captured.steps.length !== 2 ||
captured.steps.some((step) => step.outcome !== "completed") ||
!captured.steps
.at(-1)
?.after?.nodes.some(
(node) => node.title === "REA fixture incremented",
)
)
throw new Error("MCP did not observe the selected fixture's AX action");
});
scenarioStatus = "selected-AX-button-action-and-CLI-MCP-parity-observed";
}
const mismatch = await observeNativeUi(
{ ...target.value, sha256: "0".repeat(64) },
@@ -201,17 +250,24 @@ try {
target_owned: true,
};
} finally {
if (fixturePid !== undefined) {
try {
process.kill(fixturePid, "SIGTERM");
} catch (error) {
if (error.code !== "ESRCH") throw error;
if (fixturePid !== undefined && fixtureIdentity?.state === "readable") {
const current = await observeProcessStartIdentity(fixturePid);
if (current !== undefined) {
assert.ok(
current.state === "readable" &&
current.identity === fixtureIdentity.identity,
"Fixture PID identity changed; refusing to signal another process",
);
try {
process.kill(fixturePid, "SIGTERM");
} catch (cause) {
if (cause.code !== "ESRCH") throw cause;
}
}
}
if (child !== undefined && child.exitCode === null) {
const exited = new Promise((resolve) => child.once("exit", resolve));
child.kill("SIGTERM");
await exited;
await childExit;
}
await rm(root, { recursive: true, force: true });
}
+8
View File
@@ -36,6 +36,14 @@ for (const variable of ["REA_BINWALK_COMMAND", "REA_UNBLOB_COMMAND"]) {
);
await access(path);
}
try {
await exec("7z", ["i"], { timeout: 10_000 });
} catch (cause) {
throw new Error(
"verify:firmware prerequisite unavailable: Unblob's gzip/USTAR fixture extraction requires 7z on PATH",
{ cause },
);
}
const fixtureRoot = resolve(
process.env.REA_FIRMWARE_FIXTURE_ROOT ??
join(repository, "_reference/firmware-integration/generated"),