Compare commits

..
64 changed files with 512 additions and 1765 deletions
@@ -83,14 +83,6 @@ names, the native API record, and value-flow summaries. Pseudocode offsets and l
code units; use the returned `next_offset` for continuation. Provider limitations
and unavailable facts remain explicit; the complete parent Evidence is retained.
`inspect_macho` on a large framework returns megabytes of imports and exports.
Select `detail: "summary"` for slice identity, UUID and per-collection counts,
then page rows with `view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`
and `normalized_result.parent_evidence_id`. Facets are entrypoints,
architectures, build_metadata, load_commands, dependencies, imports, exports,
segments and provenance. `source_exhaustive: false` means unreturned symbols
may exist.
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
+2 -15
View File
@@ -147,8 +147,8 @@ after target content was read.
## Retained application Evidence inputs
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`,
`inspect_wasm_artifact`, and `inspect_macho` accept `detail`:
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`, and
`inspect_wasm_artifact` accept `detail`:
`complete` (default) returns the complete analysis Evidence; `summary` records
that complete Evidence in the session and returns the derived
`inspect_analysis_view` summary Evidence instead. Its
@@ -218,19 +218,6 @@ attempting oversized delivery, and returns the same summary with an exact
`parent_evidence_id` for later export or facet reads. Delivery detail does not
reach WABT or change the original source Evidence ID.
Completed `inspect_macho` Evidence supports a summary and
`view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`. Facets are
`entrypoints`, `architectures`, `build_metadata`, `load_commands`,
`dependencies`, `imports`, `exports`, `segments`, and `provenance`; pages return
the original rows. The summary keeps the selected slice, header fields and UUID,
and replaces each collection with its returned count, reported total and
`exhaustive` flag. Each page repeats the paged collection's `source_total` and
`source_exhaustive`; exhausting a non-exhaustive collection does not establish
that unreturned symbols are absent. Large frameworks return megabytes of
symbols (Electron Framework: 2.5 MB of imports and exports, 3.3 KB as a
summary), so select `detail: "summary"` on the first call. Delivery detail
never reaches the native tools or changes the source Evidence ID.
`trace_application_feature`, `trace_javascript_semantics`,
`compare_application_versions`, `compare_source_to_bundle`, and
`compare_javascript_export_shapes` accept complete inline application Evidence
+3 -5
View File
@@ -199,11 +199,9 @@ export class JadxMcpTransport implements Transport {
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
this.#appendFrame(fragment, frameBytes);
if (newline === -1) return;
const line = new TextDecoder("utf-8", {
fatal: true,
// Preserve a leading BOM so the JSON-RPC parser can reject it.
ignoreBOM: true,
}).decode(this.#frameBuffer.subarray(0, this.#frameLength));
const line = this.#frameBuffer
.subarray(0, this.#frameLength)
.toString("utf8");
this.#frameBuffer = Buffer.alloc(0);
this.#frameLength = 0;
this.onmessage?.(deserializeMessage(line));
@@ -809,42 +809,6 @@ it("keeps an active script message bucket after its last message is evicted", as
await manager.closeAll();
});
it("retains the newest contiguous messages across repeated budget evictions", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
expect(started.ok).toBe(true);
if (!started.ok) return;
bindings.device.session.nextPayload = { index: -1 };
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({index: -1});",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
// About 500 of these fit the 16 MiB budget, so 2,000 sends evict and
// compact the queue several times.
const filler = "x".repeat(32_000);
for (let index = 0; index < 2_000; index += 1)
script.message.emit({ type: "send", payload: { index, filler } }, null);
const status = manager.status(started.value.sessionId);
expect(status?.messagesTruncated).toBe(true);
const indexes = (status?.messages ?? []).map(
(message) => (message as { payload: { index: number } }).payload.index,
);
expect(indexes.length).toBeGreaterThan(400);
expect(indexes.at(-1)).toBe(1_999);
expect(indexes).toEqual(
Array.from(
{ length: indexes.length },
(_, offset) => 2_000 - indexes.length + offset,
),
);
await manager.closeAll();
});
it("serializes a final remote release against a new same-endpoint session", async () => {
const bindings = new FakeDeviceManager();
let enteredRemoval: (() => void) | undefined;
+1 -3
View File
@@ -81,9 +81,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
if (!captured.ok)
throw new ArtifactReaderFailure(
captured.error.reason === "cancelled" ? "cancelled" : "unavailable",
captured.error.detail === null
? "lipo could not enumerate universal Mach-O slices"
: `lipo could not enumerate universal Mach-O slices: ${captured.error.detail}`,
"lipo could not enumerate universal Mach-O slices",
{
cause: captured.error,
...(captured.error.cleanupFailure === null &&
+11 -22
View File
@@ -280,11 +280,9 @@ export class SafeOutputTree {
}
/** Sync the owned output tree and prevent further writes through this instance. */
async commit(signal?: AbortSignal): Promise<void> {
async commit(): Promise<void> {
this.#assertWritable();
abortIfNeeded(signal);
await this.#assertOwnedDirectories();
abortIfNeeded(signal);
// Windows has no directory fsync; file contents are already synced in write().
if (this.platform === "win32") {
this.#published = true;
@@ -317,7 +315,6 @@ export class SafeOutputTree {
);
await output.handle.sync();
await parent.handle.sync();
abortIfNeeded(signal);
this.#published = true;
} catch (cause: unknown) {
sync = { kind: "failed", cause };
@@ -339,26 +336,23 @@ export class SafeOutputTree {
closeFailure,
this.#outputRoot,
);
if (sync.kind === "failed") {
const primary = isCancellationFailure(sync.cause)
? sync.cause
: new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
);
throw ArtifactReaderFailure.withCleanup(primary, cleanup);
}
if (sync.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
),
cleanup,
);
throw ArtifactReaderFailure.withCleanup(closeFailure, cleanup);
}
if (sync.kind === "failed") {
if (isCancellationFailure(sync.cause)) throw sync.cause;
if (sync.kind === "failed")
throw new ArtifactReaderFailure(
"path",
"Could not durably sync extraction output",
{ cause: sync.cause },
);
}
}
/** Remove only this operation's unsealed tree and verify absence. */
@@ -596,11 +590,6 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
);
};
const isCancellationFailure = (
cause: unknown,
): cause is ArtifactReaderFailure =>
cause instanceof ArtifactReaderFailure && cause.reason === "cancelled";
const isAlreadyExists = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
@@ -249,7 +249,7 @@ const materializeSelection = async ({
compareUnicodeCodePoints(left.relative_path, right.relative_path),
);
completed = createExtractionResult(input, inventory, selected, extracted);
await output.commit(signal);
await output.commit();
return completed;
} catch (cause: unknown) {
const cleanupFailures = await releaseExtractionOwners(
@@ -91,7 +91,7 @@ export const browserScenarioCaptureData = (input: {
network_content: input.scenario.capture.network,
event_families: [...new Set(input.scenario.capture.events)].sort(),
},
duration_ms: Math.max(0, Math.round(performance.now() - input.startedAt)),
duration_ms: Date.now() - input.startedAt,
steps: [...input.steps],
events,
limitations: [
@@ -303,7 +303,6 @@ describe("PlaywrightBrowserScenarioProvider", () => {
});
expect(result.value.limitations).toContain(session.eventGaps[0]);
});
it("returns an initial state and every step beyond the former action ceiling", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider(() =>
@@ -377,35 +376,6 @@ describe("PlaywrightBrowserScenarioProvider", () => {
});
});
describe("PlaywrightBrowserScenarioProvider timing", () => {
it("keeps capture elapsed values valid across a backward wall-clock jump", async () => {
let wallClock = 10_000;
vi.spyOn(Date, "now").mockImplementation(() => wallClock);
const session = new FakeSession("launch");
session.onPerform = () => {
wallClock = 1;
};
const provider = new PlaywrightBrowserScenarioProvider(() =>
Promise.resolve(session),
);
try {
const result = await provider.captureScenario(scenario());
if (!result.ok) throw result.error;
expect(wallClock).toBe(1);
expect(Number.isInteger(result.value.duration_ms)).toBe(true);
expect(result.value.duration_ms).toBeGreaterThanOrEqual(0);
expect(
result.value.steps.every(
({ elapsed_ms }) => Number.isInteger(elapsed_ms) && elapsed_ms >= 0,
),
).toBe(true);
} finally {
vi.restoreAllMocks();
}
});
});
describe("PlaywrightBrowserScenarioProvider comparison coverage", () => {
it("keeps quiet captures with different event families from comparing unchanged", async () => {
const capture = async (events: readonly BrowserScenarioEventFamily[]) => {
@@ -172,7 +172,7 @@ const executeStep = async (input: {
),
});
const actionStartedAt = performance.now();
const actionStartedAt = Date.now();
session.setStep(stepIndex);
const requestCancelled = (): boolean => signal?.aborted === true;
let outcome: BrowserScenarioStepOutcome = {
@@ -200,7 +200,7 @@ const executeStep = async (input: {
stepId: action.step_id,
action: action.action,
...outcome,
elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),
elapsedMs: Date.now() - actionStartedAt,
beforeUrl,
afterUrl: session.sanitizeUrl(session.currentUrl()),
eventStart,
@@ -233,7 +233,7 @@ const runScenario = async (
): Promise<BrowserScenarioCapture> => {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = performance.now();
const startedAt = Date.now();
const session = await openSession(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
retainCleanup,
@@ -250,7 +250,7 @@ const runScenario = async (
await initialStep({
session,
scenario,
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
elapsedMs: Date.now() - startedAt,
signal: options.signal,
}),
);
+4 -10
View File
@@ -72,7 +72,7 @@ export const runElectronActions = async (
): Promise<ElectronActions> => {
const actions: ElectronActions = [];
for (const action of input.actions) {
const actionStartedAt = performance.now();
const actionStartedAt = Date.now();
const windowIndex = actionWindowIndex(action);
let selectedWindow: Page | undefined;
try {
@@ -107,10 +107,7 @@ export const runElectronActions = async (
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: "completed",
elapsed_ms: Math.max(
0,
Math.round(performance.now() - actionStartedAt),
),
elapsed_ms: Date.now() - actionStartedAt,
error: null,
});
} catch (cause: unknown) {
@@ -121,10 +118,7 @@ export const runElectronActions = async (
target:
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
status: options.signal?.aborted ? "cancelled" : "failed",
elapsed_ms: Math.max(
0,
Math.round(performance.now() - actionStartedAt),
),
elapsed_ms: Date.now() - actionStartedAt,
error: safeActionErrorMessage(cause),
});
break;
@@ -372,7 +366,7 @@ export const runWithExecutionLimits = async <Value>(
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new BrowserObservationError(OPERATION, "timeout")),
Math.max(1, deadline - performance.now()),
Math.max(1, deadline - Date.now()),
);
}),
);
@@ -86,7 +86,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
await prepareProcessOwnershipInspection(options.signal);
const startupDeadline = performance.now() + STARTUP_TIMEOUT_MS;
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
paths = {
executable: input.executable_path,
application: input.application_path,
@@ -101,7 +101,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
cwd: paths.root,
env: safeElectronEnvironment(this.environment, runId),
args: ["-r", hookPath, paths.application, ...input.args],
timeout: Math.max(1, startupDeadline - performance.now()),
timeout: Math.max(1, startupDeadline - Date.now()),
});
const leaderPid = application.process().pid;
if (
@@ -128,7 +128,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
const state = await runWithExecutionLimits(
readApplicationState(application),
undefined,
options.signal?.aborted ? performance.now() + 5_000 : undefined,
options.signal?.aborted ? Date.now() + 5_000 : undefined,
);
capture = projectElectronActiveCapture(paths, actions, state);
outcome = options.signal?.aborted
@@ -187,7 +187,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
await runWithExecutionLimits(
application.close(),
undefined,
performance.now() + 5_000,
Date.now() + 5_000,
);
} catch (cause: unknown) {
closeError = cause;
@@ -7,10 +7,7 @@ import {
} from "../domain/analysisErrorCore.js";
describe("withPlaywrightExecutionBoundary", () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
afterEach(() => vi.useRealTimers());
it("rejects work that exceeds its absolute remaining duration", async () => {
vi.useFakeTimers();
@@ -34,20 +31,4 @@ describe("withPlaywrightExecutionBoundary", () => {
controller.abort();
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
});
it("keeps its timeout stable across a wall-clock jump", async () => {
vi.spyOn(Date, "now")
.mockReturnValueOnce(1_000)
.mockReturnValue(10_000_000);
await expect(
withPlaywrightExecutionBoundary(
() =>
new Promise<string>((resolve) =>
setTimeout(() => resolve("done"), 5),
),
1_000,
),
).resolves.toBe("done");
});
});
+2 -2
View File
@@ -19,10 +19,10 @@ export const withPlaywrightExecutionBoundary = <Value>(
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline =
timeoutMs === undefined ? undefined : performance.now() + timeoutMs;
timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
const scheduleTimeout = (): void => {
if (deadline === undefined) return;
const remaining = deadline - performance.now();
const remaining = deadline - Date.now();
if (remaining <= 0) {
fail(new AnalysisTimeoutError(OPERATION, timeoutMs ?? 0));
return;
+1 -1
View File
@@ -133,7 +133,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
if (secrets === undefined)
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const startedAt = performance.now();
const startedAt = Date.now();
const opening = openPlaywrightScenarioBrowser(scenario, environment, {
signal: options.signal,
...(options.retainCleanup === undefined
+3 -3
View File
@@ -86,7 +86,7 @@ export const fetchWebSourceMaps = async (
signal?.addEventListener("abort", abortFromCaller, { once: true });
const operationSignal = operationController.signal;
const deadlineAt =
performance.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
Date.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
const budget = {
retainedBytes: 0,
deadlineAt,
@@ -110,7 +110,7 @@ export const fetchWebSourceMaps = async (
}
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
budget.decodedRecords.expandedBytes += reservation;
if (operationSignal.aborted || performance.now() >= deadlineAt) {
if (operationSignal.aborted || Date.now() >= deadlineAt) {
items.push(
emptySourceMapItem(
request,
@@ -789,7 +789,7 @@ const checkOperation = (
): void => {
if (callerSignal?.aborted === true) throw callerSignal.reason;
if (operationSignal?.aborted === true) throw operationSignal.reason;
if (performance.now() >= deadlineAt) throw new SourceMapDeadlineError();
if (Date.now() >= deadlineAt) throw new SourceMapDeadlineError();
};
const approvedUrl = (
+1 -1
View File
@@ -113,7 +113,7 @@ export const publishWebScripts = async (
options.signal,
);
options.signal?.throwIfAborted();
await tree.commit(options.signal);
await tree.commit();
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
+2 -2
View File
@@ -175,7 +175,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined, operation);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
@@ -406,7 +406,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner, operation);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
File diff suppressed because one or more lines are too long
+2 -10
View File
@@ -11,7 +11,6 @@ import { jsonValueSchema } from "../../domain/jsonValue.js";
import { localPathStringSchema } from "../../domain/localPath.js";
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
import { analysisDetailSchema } from "../analysisDetail.js";
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_macho: {},
@@ -95,15 +94,8 @@ export const NATIVE_TOOL_CONTRACTS = [
),
native(
"inspect_macho",
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper. Large frameworks return megabytes of symbols; detail summary retains the complete Evidence and returns slice identity with per-collection counts, then page rows with inspect_analysis_view kind macho.",
z.object({
detail: analysisDetailSchema
.unwrap()
.optional()
.describe(
"Omitted or complete returns the complete inspection Evidence. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; use normalized_result.parent_evidence_id for macho pages.",
),
}),
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper.",
z.object({}),
),
native(
"inspect_signature",
+1 -4
View File
@@ -1,7 +1,6 @@
import { z } from "zod";
import {
artifactInventorySummaryViewResultSchema,
machoSummaryViewResultSchema,
managedArtifactSummaryViewResultSchema,
} from "../domain/analysisView/analysisView.js";
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
@@ -382,9 +381,7 @@ export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
observe_native_ui: evidenceResultOf(nativeUiResultSchema),
capture_native_ui_scenario: evidenceResultOf(nativeUiResultSchema),
observe_native_calls: evidenceResultOf(nativeCallObservationResultSchema),
inspect_macho: evidenceResultOf(
z.union([inspectMachoSchema, machoSummaryViewResultSchema]),
),
inspect_macho: evidenceResultOf(inspectMachoSchema),
inspect_signature: evidenceResultOf(inspectSignatureSchema),
inspect_plist: evidenceResultOf(inspectPlistSchema),
list_architectures: evidenceResultOf(listArchitecturesSchema),
+1 -28
View File
@@ -55,13 +55,6 @@ import {
wasmViewItemSchema,
wasmSummarySchema,
} from "./wasmArtifactView.js";
import {
machoSummarySchema,
machoViewContextSchema,
machoViewItemSchema,
machoViewRequestSchema,
projectMachoView,
} from "./machoView.js";
import {
projectWebNetworkCaptureView,
captureViewRequestSchema,
@@ -203,7 +196,6 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
nativeViewSchema,
inventoryViewSchema,
wasmViewRequestSchema,
machoViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
androidViewRequestSchema,
@@ -323,7 +315,6 @@ const viewResultBase = {
"inspect_artifact",
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_macho",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_web_network_capture",
@@ -373,13 +364,6 @@ export const wasmArtifactSummaryViewResultSchema = z.strictObject({
summary: wasmSummarySchema,
});
/** Exact slice identity and collection counts for Mach-O's selected delivery. */
export const machoSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_macho"),
summary: machoSummarySchema,
});
/** Exact inferred-interface summary for EVM's caller-selected delivery. */
export const evmInterfaceSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -441,7 +425,6 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
javascriptSummarySchema,
inventorySummarySchema,
wasmSummarySchema,
machoSummarySchema,
evmSummarySchema,
managedSummarySchema,
captureSummarySchema,
@@ -504,14 +487,6 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
item: wasmViewItemSchema,
...viewResultBase,
}),
z.strictObject({
kind: z.literal("macho"),
view: machoViewRequestSchema,
item: machoViewItemSchema,
...viewResultBase,
...machoViewContextSchema.shape,
parent_operation: z.literal("inspect_macho"),
}),
z.strictObject({
kind: z.literal("evm"),
view: evmViewRequestSchema,
@@ -608,7 +583,6 @@ export type UnsignedAnalysisView =
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "macho" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
@@ -672,7 +646,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, Mach-O, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -699,7 +673,6 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_macho", projectMachoView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
-246
View File
@@ -1,246 +0,0 @@
import { describe, expect, it } from "vitest";
import {
projectAnalysisView,
type AnalysisViewParent,
} from "./analysisView.js";
const symbol = (name: string) => ({
name,
address: null,
weak: null,
reexport: null,
source: "libSystem",
});
const coverage = <T>(items: T[], exhaustive = true) => ({
items,
total: exhaustive ? items.length : null,
exhaustive,
limitations: exhaustive ? [] : ["nm output may omit stripped symbols."],
});
const report = {
format: "mach-o",
selected_architecture: { name: "arm64", container_file_offset: 0 },
endian: null,
word_size: 64,
file_type: "2",
flags: ["0x00200085"],
uuid: "4C4C44E9-5555-3144-A1E9-D858E24A1CCE",
entrypoints: coverage([{ file_offset: 16384 }]),
architectures: coverage([
{
name: "arm64",
cpu_type: "16777228",
cpu_subtype: "0",
file_offset: 0,
size: 4096,
alignment: 14,
},
]),
build_metadata: coverage([
{ platform: "1", minimum_os: "14.0", sdk: "15.0", tools: [] },
]),
load_commands: coverage([{ index: 0, kind: "LC_MAIN", fields: {} }]),
dependencies: coverage([
{
path: "/usr/lib/libSystem.B.dylib",
kind: "LC_LOAD_DYLIB",
current_version: "1351.0.0",
compatibility_version: "1.0.0",
},
]),
imports: coverage(
["_malloc", "_free", "_open"].map((name) => symbol(name)),
false,
),
exports: coverage([symbol("__mh_execute_header")]),
segments: coverage([
{
name: "__TEXT",
vm_address: "0x100000000",
vm_size: 16384,
file_offset: 0,
file_size: 16384,
maximum_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
initial_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
sections: coverage([]),
},
]),
provenance: [
{
tool: "nm",
command: ["/usr/bin/nm", "$ARTIFACT"],
tool_version: null,
version_reason: "fixture",
executable_sha256: "a".repeat(64),
exit: { code: 0, signal: null },
stdout_bytes: 10,
stderr_bytes: 0,
},
],
limitations: ["Imports and exports combine dyld_info and nm."],
};
const parent = (
normalizedResult: unknown = report,
subject: AnalysisViewParent["subject"] = {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "mach-o",
architecture: "arm64",
local_path: "/bin/tool",
},
): AnalysisViewParent => ({
evidenceId: `ev_${"c".repeat(64)}`,
operation: "inspect_macho",
normalizedResult,
subject,
limitations: ["Parent limitation."],
});
describe("Mach-O analysis views", () => {
it("summarizes slice identity and collection counts without rows", () => {
const projected = projectAnalysisView(parent(), { kind: "summary" });
if (!projected.ok) throw projected.error;
expect(projected.value).toMatchObject({
kind: "summary",
parent_operation: "inspect_macho",
artifact: { path: "/bin/tool", sha256: "b".repeat(64) },
summary: {
selected_architecture: { name: "arm64", container_file_offset: 0 },
uuid: report.uuid,
collections: {
imports: { returned: 3, total: null, exhaustive: false },
exports: { returned: 1, total: 1, exhaustive: true },
segments: { returned: 1, total: 1, exhaustive: true },
},
provenance_count: 1,
limitation_count: 3,
},
coverage: { status: "complete-within-view", examined: 10, total: 10 },
limitations: [
"Imports and exports combine dyld_info and nm.",
"Parent limitation.",
"nm output may omit stripped symbols.",
],
unknowns: [expect.stringContaining("exhaustive imports;")],
});
expect(JSON.stringify(projected.value)).not.toContain("_malloc");
});
it("pages original rows with the producer's own coverage", () => {
const first = projectAnalysisView(parent(), {
kind: "macho",
facet: "imports",
offset: 1,
limit: 1,
});
if (!first.ok) throw first.error;
expect(first.value).toMatchObject({
kind: "macho",
item: [symbol("_free")],
source_total: null,
source_exhaustive: false,
coverage: { status: "page", examined: 1, total: 3, next_offset: 2 },
});
expect(first.value.limitations).toContain(
"nm output may omit stripped symbols.",
);
// Rows whose keys include an earlier row shape's keys stay whole.
for (const facet of ["architectures", "segments"] as const) {
const page = projectAnalysisView(parent(), {
kind: "macho",
facet,
offset: 0,
limit: 64,
});
if (!page.ok) throw page.error;
expect(page.value.kind === "macho" && page.value.item).toEqual(
report[facet].items,
);
}
const provenance = projectAnalysisView(parent(), {
kind: "macho",
facet: "provenance",
offset: 0,
limit: 64,
});
if (!provenance.ok) throw provenance.error;
expect(provenance.value).toMatchObject({
item: report.provenance,
source_total: 1,
source_exhaustive: true,
coverage: { exhausted: true, next_offset: null },
});
const past = projectAnalysisView(parent(), {
kind: "macho",
facet: "exports",
offset: 5,
limit: 64,
});
if (!past.ok) throw past.error;
expect(past.value.coverage).toMatchObject({
status: "empty",
exhausted: true,
});
});
it("keeps a missing subject unknown instead of inventing identity", () => {
const projected = projectAnalysisView(parent(report, null), {
kind: "summary",
});
if (!projected.ok) throw projected.error;
expect(projected.value.artifact).toEqual({ path: "", sha256: null });
expect(projected.value.unknowns).toContain(
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
);
});
it("rejects other view kinds and malformed retained results", () => {
const wrongKind = projectAnalysisView(parent(), {
kind: "wasm",
facet: "exports",
offset: 0,
limit: 64,
});
if (wrongKind.ok) throw new Error("expected a view-kind refusal");
expect(wrongKind.error).toMatchObject({
_tag: "AnalysisInputError",
issues: [
{
path: ["view"],
message: "Mach-O inspection supports summary and macho views.",
},
],
});
const contradictory = projectAnalysisView(
parent(report, {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "elf",
architecture: null,
local_path: "/bin/tool",
}),
{ kind: "summary" },
);
if (contradictory.ok) throw new Error("expected a subject refusal");
expect(contradictory.error).toMatchObject({
issues: [{ path: ["source", "subject"] }],
});
const malformed = projectAnalysisView(
parent({ ...report, imports: { items: "x" } }),
{ kind: "summary" },
);
expect(malformed.ok).toBe(false);
if (!malformed.ok) expect(malformed.error._tag).toBe("AnalysisInputError");
});
});
-247
View File
@@ -1,247 +0,0 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { isMachOFormat } from "../binaryTargetTypes.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { inspectMachoSchema } from "../native/nativeInspection.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const MACHO_COLLECTIONS = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
] as const;
type MachoCollection = (typeof MACHO_COLLECTIONS)[number];
/** Original inspect_macho rows; offsets count rows in the retained collection. */
export const machoViewRequestSchema = z.strictObject({
kind: z.literal("macho"),
facet: z.enum([...MACHO_COLLECTIONS, "provenance"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
const { shape } = inspectMachoSchema;
/**
* Union members are tried in order and plain objects drop unknown keys, so a
* segment or architecture row would otherwise match the entrypoint row and
* lose every field but file_offset. Exact key sets keep each page's rows whole.
*/
const exactRows = <Shape extends z.ZodRawShape>(
rows: z.ZodArray<z.ZodObject<Shape>>,
) => z.array(z.strictObject(rows.element.shape));
export const machoViewItemSchema = z.union([
exactRows(shape.entrypoints.shape.items),
exactRows(shape.architectures.shape.items),
exactRows(shape.build_metadata.shape.items),
exactRows(shape.load_commands.shape.items),
exactRows(shape.dependencies.shape.items),
// Imports and exports share one row shape.
exactRows(shape.imports.shape.items),
exactRows(shape.segments.shape.items),
exactRows(shape.provenance),
]);
/** The producer's own coverage of the paged collection, not of this page. */
export const machoViewContextSchema = z.strictObject({
source_total: z.number().int().nonnegative().nullable(),
source_exhaustive: z.boolean(),
});
const collectionCountSchema = z.strictObject({
returned: z.number().int().nonnegative(),
total: z.number().int().nonnegative().nullable(),
exhaustive: z.boolean(),
});
/** Slice identity and per-collection counts without the collections themselves. */
export const machoSummarySchema = z.strictObject({
format: shape.format,
selected_architecture: shape.selected_architecture,
endian: shape.endian,
word_size: shape.word_size,
file_type: shape.file_type,
flags: shape.flags,
uuid: shape.uuid,
collections: z.strictObject(
Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [name, collectionCountSchema]),
) as Record<MachoCollection, typeof collectionCountSchema>,
),
provenance_count: z.number().int().nonnegative(),
limitation_count: z.number().int().nonnegative(),
});
type MachoReport = z.output<typeof inspectMachoSchema>;
/** Admit a well-formed report whose recorded subject, if any, is a Mach-O. */
const parseMachoReport = (
parent: AnalysisViewParent,
): Result<MachoReport, AnalysisError> => {
const parsed = inspectMachoSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
if (parent.subject != null && !isMachOFormat(parent.subject.format))
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Mach-O parent Evidence subject must identify a thin or universal Mach-O.",
},
]),
);
return ok(parsed.data);
};
/** Counts replace rows; every collection caveat stays in the limitations. */
const summarizeMacho = (
report: MachoReport,
parentLimitations: readonly string[],
) => {
const limitations = uniqueSorted([
...parentLimitations,
...report.limitations,
...MACHO_COLLECTIONS.flatMap((name) => report[name].limitations),
]);
const collections = Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [
name,
{
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
},
]),
) as Record<MachoCollection, z.output<typeof collectionCountSchema>>;
return {
limitations,
returned: MACHO_COLLECTIONS.reduce(
(sum, name) => sum + report[name].items.length,
0,
),
summary: {
format: report.format,
selected_architecture: report.selected_architecture,
endian: report.endian,
word_size: report.word_size,
file_type: report.file_type,
flags: report.flags,
uuid: report.uuid,
collections,
provenance_count: report.provenance.length,
limitation_count: limitations.length,
},
};
};
/** Project retained inspect_macho Evidence without rerunning native tools. */
export const projectMachoView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "macho")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message: "Mach-O inspection supports summary and macho views.",
},
]),
);
const parsed = parseMachoReport(parent);
if (!parsed.ok) return parsed;
const report = parsed.value;
const incomplete = MACHO_COLLECTIONS.filter(
(name) => !report[name].exhaustive,
);
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_macho" as const,
parent_digest: parent.evidenceId.slice(3),
artifact:
parent.subject == null
? { path: "", sha256: null }
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
unknowns: [
...(incomplete.length === 0
? []
: [
`Native tools did not report exhaustive ${incomplete.join(", ")}; page exhaustion does not establish absence of unreturned rows.`,
]),
...(parent.subject == null
? [
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
]
: []),
],
};
if (view.kind === "summary") {
const { summary, limitations, returned } = summarizeMacho(
report,
parent.limitations,
);
return ok({
kind: "summary",
view,
...shared,
limitations,
summary,
coverage: completeWithinViewCoverage(returned, returned),
});
}
const source =
view.facet === "provenance"
? {
items: report.provenance,
total: report.provenance.length,
exhaustive: true,
limitations: [],
}
: report[view.facet];
const item = source.items.slice(view.offset, view.offset + view.limit);
return ok({
kind: "macho",
view,
item,
...shared,
limitations: uniqueSorted([
...parent.limitations,
...report.limitations,
...source.limitations,
]),
source_total: source.total,
source_exhaustive: source.exhaustive,
coverage: pageViewCoverage(view.offset, item.length, source.items.length),
});
};
@@ -47,6 +47,10 @@ const validateCommitments = (
digestProcessCommitment(
value,
), `manifest.${field}`, "commitment does not match its canonical value");
require(Date.parse(manifest.started_at) <=
Date.parse(
manifest.completed_at,
), "manifest.completed_at", "completion precedes start");
};
const validateOrdering = (
+2 -2
View File
@@ -176,11 +176,11 @@ export const runFirmwareCommand = async (context: {
};
let failure: unknown;
try {
const deadline = performance.now() + FIRMWARE_LIMITS.timeoutMs;
const deadline = Date.now() + FIRMWARE_LIMITS.timeoutMs;
while (!(await supervisor.waitForOutputClose(100))) {
checkDiagnostics();
if (signal.aborted) throw new AnalysisCancelledError(operation);
if (performance.now() >= deadline)
if (Date.now() >= deadline)
throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);
if (context.outputBudget !== undefined)
await inventoryFirmwareOutput(
+1 -1
View File
@@ -96,7 +96,7 @@ export const publishFirmwareExtraction = async (context: {
published_bytes: files.reduce((sum, file) => sum + file.size, 0),
});
context.signal.throwIfAborted();
await tree.commit(context.signal);
await tree.commit();
return result;
} catch (cause: unknown) {
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
+23 -62
View File
@@ -83,8 +83,8 @@ interface ManagedSession extends ManagedRemoteConnection {
readonly pid: number;
readonly mode: "attach" | "spawn";
readonly scripts: Map<string, ManagedScript>;
readonly messages: MessageFifo<CapturedMessage>;
readonly messagesByScript: Map<string, MessageFifo<JsonValue>>;
readonly messages: JsonValue[];
readonly messagesByScript: Map<string, JsonValue[]>;
state: "paused" | "running" | "detached";
targetResumeObserved: boolean;
resumeAfterDetachPending: boolean;
@@ -277,7 +277,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
pid,
mode: input.mode,
scripts: new Map(),
messages: new MessageFifo(),
messages: [],
messagesByScript: new Map(),
state: input.mode === "spawn" ? "paused" : "running",
targetResumeObserved: false,
@@ -373,7 +373,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
.digest("hex");
const scriptId = randomUUID();
const scriptName = `rea-${scriptId}`;
managed.messagesByScript.set(scriptId, new MessageFifo());
managed.messagesByScript.set(scriptId, []);
let nativeScript: Script | undefined;
const onMessage = (message: FridaMessage, data: Buffer | null): void => {
this.#recordMessage(managed, scriptId, message, data);
@@ -397,7 +397,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
sourceKind: source.sourceKind,
sourcePath: source.sourceKind === "file" ? source.path : null,
sourceSha256,
messages: managed.messagesByScript.get(scriptId)?.toArray() ?? [],
messages: [...(managed.messagesByScript.get(scriptId) ?? [])],
messagesTruncated: managed.messagesTruncated,
});
} catch (cause: unknown) {
@@ -517,9 +517,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
scriptId: id,
name,
})),
messages: managed.messages
.toArray()
.map(({ observation }) => observation),
messages: [...managed.messages],
messagesTruncated: managed.messagesTruncated,
};
}
@@ -853,21 +851,30 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
return;
}
while (
managed.messages.size > 0 &&
managed.messages.length > 0 &&
managed.capturedBytes + charge > MAX_SESSION_CAPTURE_BYTES
) {
const removed = managed.messages.shift();
if (removed !== undefined) {
managed.capturedBytes -= removed.charge;
// Both queues are in arrival order, so the globally oldest message is
// also the oldest one retained for its script.
const scriptMessages = managed.messagesByScript.get(removed.scriptId);
if (scriptMessages?.peek() === removed.observation)
scriptMessages.shift();
managed.capturedBytes -= Buffer.byteLength(JSON.stringify(removed));
if (
typeof removed === "object" &&
removed !== null &&
!Array.isArray(removed) &&
typeof removed.script_id === "string"
) {
const scriptMessages = managed.messagesByScript.get(
removed.script_id,
);
const index = scriptMessages?.indexOf(removed) ?? -1;
if (scriptMessages !== undefined && index >= 0) {
scriptMessages.splice(index, 1);
}
}
}
managed.messagesTruncated = true;
}
managed.messages.push({ observation, scriptId, charge });
managed.messages.push(observation);
managed.messagesByScript.get(scriptId)?.push(observation);
managed.capturedBytes += charge;
}
@@ -1233,49 +1240,3 @@ const providerError = (
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
interface CapturedMessage {
readonly observation: JsonValue;
readonly scriptId: string;
/** Serialized bytes charged against the session capture budget. */
readonly charge: number;
}
/**
* Arrival-ordered queue whose eviction advances a head offset. A full capture
* budget evicts on every message, and `Array#shift` would copy every retained
* message each time.
*/
class MessageFifo<T> {
#items: (T | undefined)[] = [];
#head = 0;
get size(): number {
return this.#items.length - this.#head;
}
push(item: T): void {
this.#items.push(item);
}
peek(): T | undefined {
return this.#items[this.#head];
}
shift(): T | undefined {
if (this.#head >= this.#items.length) return undefined;
const item = this.#items[this.#head];
this.#items[this.#head] = undefined;
this.#head += 1;
// Compacting once half the slots are evicted keeps eviction amortized O(1).
if (this.#head * 2 >= this.#items.length) {
this.#items = this.#items.slice(this.#head);
this.#head = 0;
}
return item;
}
toArray(): T[] {
return this.#items.slice(this.#head) as T[];
}
}
+114 -2
View File
@@ -1,4 +1,4 @@
import { parseGhidraJavaProperties } from "./GhidraJavaProperties.js";
import { err, ok, type Result } from "../domain/result.js";
/** Ghidra build whose bridge behavior this REA release verifies. */
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
@@ -61,7 +61,7 @@ const GHIDRA_RELEASE_PATTERN = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u;
export const ghidraApplicationProperties = (
content: string,
): GhidraApplicationProperties => {
const parsed = parseGhidraJavaProperties(content);
const parsed = parseJavaProperties(content);
if (!parsed.ok)
return {
providerVersion: null,
@@ -274,3 +274,115 @@ const unresolvedJavaRequirement = (
});
/** Parse Java Properties.load(InputStream) syntax from its ISO-8859-1 text. */
const parseJavaProperties = (
content: string,
): Result<ReadonlyMap<string, string>, string> => {
const values = new Map<string, string>();
for (const line of logicalPropertyLines(content)) {
let start = 0;
while (isPropertyWhitespace(line[start])) start += 1;
if (start === line.length || line[start] === "#" || line[start] === "!")
continue;
let end = start;
let escaped = false;
while (end < line.length) {
const character = line[end];
if (
!escaped &&
(character === "=" ||
character === ":" ||
isPropertyWhitespace(character))
)
break;
if (character === "\\") escaped = !escaped;
else escaped = false;
end += 1;
}
let valueStart = end;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
if (line[valueStart] === "=" || line[valueStart] === ":") valueStart += 1;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
const key = decodePropertyEscapes(line.slice(start, end));
if (!key.ok) return err(key.error);
const value = decodePropertyEscapes(line.slice(valueStart));
if (!value.ok) return err(value.error);
values.set(key.value, value.value);
}
return ok(values);
};
const isPropertyWhitespace = (value: string | undefined): boolean =>
value === " " || value === "\t" || value === "\f";
/** Join odd-backslash continuations while stripping leading continuation space. */
function* logicalPropertyLines(content: string): Generator<string> {
let physicalStart = 0;
let logical = "";
let continuing = false;
while (physicalStart <= content.length) {
let physicalEnd = physicalStart;
while (
physicalEnd < content.length &&
content[physicalEnd] !== "\n" &&
content[physicalEnd] !== "\r"
)
physicalEnd += 1;
let line = content.slice(physicalStart, physicalEnd);
let leading = 0;
while (isPropertyWhitespace(line[leading])) leading += 1;
const comment =
!continuing && (line[leading] === "#" || line[leading] === "!");
if (continuing) line = line.slice(leading);
let continued = false;
if (!comment) {
let slashes = 0;
for (
let index = line.length - 1;
index >= 0 && line[index] === "\\";
index -= 1
)
slashes += 1;
continued = slashes % 2 === 1;
logical += continued ? line.slice(0, -1) : line;
}
if (!continued) {
yield logical;
logical = "";
}
continuing = continued;
if (physicalEnd === content.length) break;
physicalStart =
content[physicalEnd] === "\r" && content[physicalEnd + 1] === "\n"
? physicalEnd + 2
: physicalEnd + 1;
}
// Properties.load still consumes the accumulated line when EOF follows a
// continuation marker; the marker itself was already removed above.
if (continuing) yield logical;
}
const decodePropertyEscapes = (value: string): Result<string, string> => {
let result = "";
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (character !== "\\") {
result += character;
continue;
}
const escaped = value[++index];
if (escaped === undefined)
return err("Trailing escape in Java properties value");
if (escaped === "t") result += "\t";
else if (escaped === "n") result += "\n";
else if (escaped === "r") result += "\r";
else if (escaped === "f") result += "\f";
else if (escaped === "u") {
const digits = value.slice(index + 1, index + 5);
if (digits.length !== 4 || !/^[0-9a-f]{4}$/iu.test(digits))
return err("Malformed Unicode escape in Java properties file");
result += String.fromCharCode(Number.parseInt(digits, 16));
index += 4;
} else result += escaped;
}
return ok(result);
};
-115
View File
@@ -1,115 +0,0 @@
import { err, ok, type Result } from "../domain/result.js";
/** Parse Java Properties.load(InputStream) syntax from its ISO-8859-1 text. */
export const parseGhidraJavaProperties = (
content: string,
): Result<ReadonlyMap<string, string>, string> => {
const values = new Map<string, string>();
for (const line of logicalPropertyLines(content)) {
let start = 0;
while (isPropertyWhitespace(line[start])) start += 1;
if (start === line.length || line[start] === "#" || line[start] === "!")
continue;
let end = start;
let escaped = false;
while (end < line.length) {
const character = line[end];
if (
!escaped &&
(character === "=" ||
character === ":" ||
isPropertyWhitespace(character))
)
break;
if (character === "\\") escaped = !escaped;
else escaped = false;
end += 1;
}
let valueStart = end;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
if (line[valueStart] === "=" || line[valueStart] === ":") valueStart += 1;
while (isPropertyWhitespace(line[valueStart])) valueStart += 1;
const key = decodePropertyEscapes(line.slice(start, end));
if (!key.ok) return err(key.error);
const value = decodePropertyEscapes(line.slice(valueStart));
if (!value.ok) return err(value.error);
values.set(key.value, value.value);
}
return ok(values);
};
const isPropertyWhitespace = (value: string | undefined): boolean =>
value === " " || value === "\t" || value === "\f";
/** Join odd-backslash continuations while stripping leading continuation space. */
function* logicalPropertyLines(content: string): Generator<string> {
let physicalStart = 0;
let logical = "";
let continuing = false;
while (physicalStart <= content.length) {
let physicalEnd = physicalStart;
while (
physicalEnd < content.length &&
content[physicalEnd] !== "\n" &&
content[physicalEnd] !== "\r"
)
physicalEnd += 1;
let line = content.slice(physicalStart, physicalEnd);
let leading = 0;
while (isPropertyWhitespace(line[leading])) leading += 1;
const comment =
!continuing && (line[leading] === "#" || line[leading] === "!");
if (continuing) line = line.slice(leading);
let continued = false;
if (!comment) {
let slashes = 0;
for (
let index = line.length - 1;
index >= 0 && line[index] === "\\";
index -= 1
)
slashes += 1;
continued = slashes % 2 === 1;
logical += continued ? line.slice(0, -1) : line;
}
if (!continued) {
yield logical;
logical = "";
}
continuing = continued;
if (physicalEnd === content.length) break;
physicalStart =
content[physicalEnd] === "\r" && content[physicalEnd + 1] === "\n"
? physicalEnd + 2
: physicalEnd + 1;
}
// Properties.load still consumes the accumulated line when EOF follows a
// continuation marker; the marker itself was already removed above.
if (continuing) yield logical;
}
const decodePropertyEscapes = (value: string): Result<string, string> => {
let result = "";
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (character !== "\\") {
result += character;
continue;
}
const escaped = value[++index];
if (escaped === undefined)
return err("Trailing escape in Java properties value");
if (escaped === "t") result += "\t";
else if (escaped === "n") result += "\n";
else if (escaped === "r") result += "\r";
else if (escaped === "f") result += "\f";
else if (escaped === "u") {
const digits = value.slice(index + 1, index + 5);
if (digits.length !== 4 || !/^[0-9a-f]{4}$/iu.test(digits))
return err("Malformed Unicode escape in Java properties file");
result += String.fromCharCode(Number.parseInt(digits, 16));
index += 4;
} else result += escaped;
}
return ok(result);
};
+11 -12
View File
@@ -13,7 +13,6 @@ import {
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
import { parseGhidraJavaProperties } from "./GhidraJavaProperties.js";
/** Installed processor code and data, distinct from REA's analysis-extension ABI. */
export const ghidraPspExtensionSchema = z.strictObject({
@@ -89,7 +88,7 @@ export const inspectGhidraPspExtension = async (
throw new Error("The installed Allegrex extension has no loader JAR.");
const hash = createHash("sha256");
let bytesRead = 0;
let properties = Buffer.alloc(0);
let properties = "";
for (const relative of files) {
signal?.throwIfAborted();
const path = join(root, relative);
@@ -136,22 +135,22 @@ export const inspectGhidraPspExtension = async (
);
bytesRead += before.size;
if (relative === "extension.properties")
properties = Buffer.concat(chunks);
properties = Buffer.concat(chunks).toString("utf8");
} finally {
await handle.close();
}
}
// Ghidra's extension.properties version is the compatible Ghidra version,
// not the extension release (e.g. v21.4); content identity supplies the latter.
const parsedProperties = parseGhidraJavaProperties(
properties.toString("latin1"),
);
if (!parsedProperties.ok)
throw new Error(
`Invalid Allegrex extension properties: ${parsedProperties.error}`,
);
const property = (name: string): string | undefined =>
parsedProperties.value.get(name);
const property = (name: string): string => {
const values = properties.split(/\r?\n/u).flatMap((line) => {
const match = /^\s*([A-Za-z][A-Za-z0-9]*)\s*=\s*(.*?)\s*$/u.exec(line);
return match?.[1] === name ? [match[2] ?? ""] : [];
});
if (values.length !== 1)
throw new Error(`Allegrex extension must declare exactly one ${name}.`);
return values[0] ?? "";
};
if (
property("name") !== "ghidra-allegrex" ||
property("version") !== ghidraVersion
+1 -1
View File
@@ -279,6 +279,6 @@ export const checkRecoveryDeadline = (
signal?: AbortSignal,
): void => {
checkRecoveryCancellation(signal);
if (performance.now() >= deadline)
if (Date.now() >= deadline)
throw new AnalysisTimeoutError(OPERATION, RECOVERY_LIMITS.timeoutMs);
};
@@ -33,7 +33,7 @@ it("rejects an exhausted shared execution budget before launching the next comma
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: performance.now() - 1,
deadline: Date.now() - 1,
launcher: async () => {
throw new Error("An expired budget must not launch");
},
@@ -52,7 +52,7 @@ it("preserves caller cancellation before acquiring an expired execution budget",
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: performance.now() - 1,
deadline: Date.now() - 1,
signal: AbortSignal.abort(),
launcher: async () => {
throw new Error("A cancelled request must not launch");
@@ -86,7 +86,7 @@ const commandFixture = (
arguments: ["--version"],
cwd: "/tmp/unused",
environment: {},
deadline: performance.now() + 5_000,
deadline: Date.now() + 5_000,
launcher,
},
};
@@ -140,7 +140,7 @@ it("enforces the shared deadline while exited output streams remain open", async
});
try {
await expect(
runWakaruCommand({ ...context, deadline: performance.now() + 50 }),
runWakaruCommand({ ...context, deadline: Date.now() + 50 }),
).rejects.toMatchObject({
_tag: "AnalysisTimeoutError",
operation: "recover_javascript_sources",
+2 -2
View File
@@ -100,7 +100,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
let tree: SafeOutputTree | undefined;
let failed: { readonly cause: unknown } | undefined;
let execution: AnalysisExecution | undefined;
const deadline = performance.now() + RECOVERY_LIMITS.timeoutMs;
const deadline = Date.now() + RECOVERY_LIMITS.timeoutMs;
try {
checkRecoveryCancellation(options?.signal);
const engine = await resolveWakaruCommand(this.environment);
@@ -139,7 +139,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort {
await rm(root, { recursive: true, force: true });
root = undefined;
checkRecoveryDeadline(deadline, options?.signal);
await tree.commit(options?.signal);
await tree.commit();
} catch (cause: unknown) {
failed = { cause };
}
+73 -73
View File
@@ -1,7 +1,6 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { Formatter, Help, z } from "incur";
import { performance } from "node:perf_hooks";
import { resolve } from "node:path";
import { CATALOG_IDENTITY } from "./catalogIdentity.js";
@@ -75,15 +74,14 @@ interface McpDoctorCheck {
/** Diagnose the actual production stdio adapter with one startup-bounded SDK session. */
export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
const deadline =
performance.now() +
(options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs);
Date.now() + (options.deadlineMs ?? MCP_STARTUP_POLICY.doctorDeadlineMs);
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(new Error("Production MCP doctor deadline expired")),
Math.max(1, Math.ceil(deadline - performance.now())),
Math.max(1, deadline - Date.now()),
);
const stderr = captureStderr();
const transport = new OwnedStdioClientTransport({
const transport = new TrackedStdioClientTransport({
command: options.command,
args: [...options.args],
cwd: options.cwd,
@@ -92,20 +90,21 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
});
transport.stderr?.on("data", stderr.append);
const client = new Client({ name: "rea-mcp-doctor", version: "1" });
let result: ProductionMcpDoctorResult;
let cleanupFailure: { readonly cause: unknown } | undefined;
try {
await client.connect(
transport,
requestOptions(deadline, controller.signal),
);
result = await inspectProductionMcpSession(
client,
deadline,
controller.signal,
);
return {
...(await inspectProductionMcpSession(
client,
deadline,
controller.signal,
)),
diagnostics: stderr.value(),
};
} catch (cause: unknown) {
result = {
return {
healthy: false,
adapter: "production-stdio" as const,
server: null,
@@ -119,71 +118,14 @@ export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
detail: errorMessage(cause),
},
],
diagnostics: stderr.value(),
};
} finally {
clearTimeout(timer);
try {
await client.close();
} catch (cause: unknown) {
cleanupFailure = { cause };
}
try {
// An interrupted connect can clear the client's transport reference
// before its startup child is closed. The transport retains that child.
await transport.close();
} catch (cause: unknown) {
cleanupFailure = {
cause:
cleanupFailure === undefined || cleanupFailure.cause === cause
? cause
: new AggregateError(
[cleanupFailure.cause, cause],
`MCP client and transport cleanup failed: ${errorMessage(cleanupFailure.cause)}; ${errorMessage(cause)}`,
),
};
}
await closeMcpChild(client, transport);
}
if (cleanupFailure !== undefined)
result = {
...result,
healthy: false,
checks: [
...result.checks,
{
name: "cleanup",
ok: false,
detail: `MCP stdio cleanup failed: ${errorMessage(cleanupFailure.cause)}`,
},
],
};
return { ...result, diagnostics: stderr.value() };
};
type ProductionMcpDoctorResult =
| Awaited<ReturnType<typeof inspectProductionMcpSession>>
| {
readonly healthy: false;
readonly adapter: "production-stdio";
readonly server: null;
readonly inventory: null;
readonly identity: null;
readonly request_flow: {
readonly tool: "binary_session";
readonly ok: false;
};
readonly checks: readonly McpDoctorCheck[];
};
/** Join SDK-triggered and caller-triggered close calls for the same child. */
class OwnedStdioClientTransport extends StdioClientTransport {
#closePromise: Promise<void> | undefined;
override close(): Promise<void> {
this.#closePromise ??= super.close();
return this.#closePromise;
}
}
const inspectProductionMcpSession = async (
client: Client,
deadline: number,
@@ -443,7 +385,7 @@ const isOutputFormat = (value: string | undefined): value is OutputFormat =>
const requestOptions = (deadline: number, signal: AbortSignal) => ({
signal,
timeout: Math.max(1, Math.ceil(deadline - performance.now())),
timeout: Math.max(1, deadline - Date.now()),
});
const targetFreeEnvironment = (
@@ -486,3 +428,61 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
class TrackedStdioClientTransport extends StdioClientTransport {
spawnedPid: number | null = null;
override async start(): Promise<void> {
await super.start();
this.spawnedPid = this.pid;
}
}
const closeMcpChild = async (
client: Client,
transport: TrackedStdioClientTransport,
): Promise<void> => {
const pid = transport.spawnedPid ?? transport.pid;
await Promise.allSettled([client.close()]);
await Promise.allSettled([transport.close()]);
if (pid === null || !(await processExists(pid))) return;
await terminateProcess(pid, "SIGTERM");
if (await waitForProcessExit(pid, 1_000)) return;
await terminateProcess(pid, "SIGKILL");
await waitForProcessExit(pid, 1_000);
};
const terminateProcess = async (
pid: number,
signal: NodeJS.Signals,
): Promise<void> => {
try {
process.kill(pid, signal);
} catch (cause: unknown) {
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
throw cause;
}
};
const waitForProcessExit = async (
pid: number,
timeoutMs: number,
): Promise<boolean> => {
const deadline = Date.now() + timeoutMs;
do {
if (!(await processExists(pid))) return true;
await new Promise<void>((resolve) => setTimeout(resolve, 20));
} while (Date.now() < deadline);
return !(await processExists(pid));
};
const processExists = async (pid: number): Promise<boolean> => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
return false;
throw cause;
}
};
+1 -18
View File
@@ -4,7 +4,6 @@ import { createReadStream } from "node:fs";
import { realpath } from "node:fs/promises";
import { err, ok, type Result } from "../domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
import {
OwnedCommandFailure,
runOwnedCommand,
@@ -40,7 +39,6 @@ export interface NativeCommandCapture {
export class NativeCommandFailure extends Error {
readonly cleanupOwner: ProviderProcessSupervisor | undefined;
readonly cleanupFailures: readonly NativeCommandCleanupFailure[];
readonly detail: string | null;
constructor(
readonly tool: string,
@@ -60,7 +58,6 @@ export class NativeCommandFailure extends Error {
super(`Native command ${tool} failed: ${reason}`, options);
this.cleanupOwner = options?.cleanupOwner;
this.cleanupFailures = options?.cleanupFailures ?? [];
this.detail = options?.detail ?? null;
}
}
@@ -70,8 +67,6 @@ export interface NativeCommandFailureOptions extends ErrorOptions {
readonly cleanupOwner?: ProviderProcessSupervisor;
/** All owners still incomplete after a preflight retry blocked this command. */
readonly cleanupFailures?: readonly NativeCommandCleanupFailure[];
/** Host-side reason the command could not be supervised, such as a missing ownership helper compiler. */
readonly detail?: string;
}
/** One failed cleanup attempt; the runner retains `owner` until it is verified stopped. */
@@ -315,9 +310,6 @@ export const resolveXcrunTool = async (
...(found.error.cleanupFailures.length === 0
? {}
: { cleanupFailures: found.error.cleanupFailures }),
...(found.error.detail === null
? {}
: { detail: found.error.detail }),
},
found.error.capture,
found.error.cleanupFailure,
@@ -457,16 +449,7 @@ const captureProcess = async (
),
);
}
return err(
new NativeCommandFailure(tool, "io", null, {
cause,
// Process supervision needs the Darwin ownership helper; its typed
// message names the compiler or SDK prerequisite to fix.
...(cause instanceof DarwinProcessOwnershipInspectionError
? { detail: cause.message }
: {}),
}),
);
return err(new NativeCommandFailure(tool, "io", null, { cause }));
}
};
-1
View File
@@ -966,7 +966,6 @@ const translateCommandFailure = (
signal: failure.capture?.signal ?? null,
stdout_bytes: failure.capture?.stdoutBytes ?? 0,
stderr_bytes: failure.capture?.stderrBytes ?? 0,
...(failure.detail === null ? {} : { detail: failure.detail }),
},
});
};
+29 -11
View File
@@ -33,7 +33,10 @@ export type ArtifactAnalysisRuntime = Pick<
/** Own admission, artifact descriptors, producer cleanup and private workspaces together. */
export class ArtifactAnalysisResources {
readonly #artifacts = new ArtifactResourceScope();
readonly #artifacts: {
readonly scope: ArtifactResourceScope;
operation: string;
};
readonly #pending = new Map<
ArtifactAnalysisRuntime,
{
@@ -54,7 +57,9 @@ export class ArtifactAnalysisResources {
readonly message: string;
readonly details: Readonly<Record<string, JsonValue>>;
},
) {}
) {
this.#artifacts = { scope: new ArtifactResourceScope(), operation };
}
run<T>(
work: () => Promise<Result<T, AnalysisError>>,
@@ -76,8 +81,15 @@ export class ArtifactAnalysisResources {
);
this.#busy = true;
const running = this.#tail
.then(() => this.#artifacts.run(work))
.catch((cause: unknown) => err(this.#artifactFailure(cause, operation)))
.then(() =>
this.#artifacts.scope.run(() => {
// Failed descriptor cleanup still belongs to the preceding request until
// this scope has drained it and admits acquisition for the new request.
this.#artifacts.operation = operation;
return work();
}),
)
.catch((cause: unknown) => err(this.#artifactFailure(cause)))
.finally(() => {
this.#busy = false;
});
@@ -94,20 +106,23 @@ export class ArtifactAnalysisResources {
maximumBytes,
signal,
undefined,
this.#artifacts,
this.#artifacts.scope,
);
}
readLimits(limits: LinuxResourceLimits): Promise<LinuxResourceLimits> {
return this.readKernelLimits(limits, this.#artifacts);
return this.readKernelLimits(limits, this.#artifacts.scope);
}
retain(
root: ArtifactAnalysisRuntime,
owner?: ProviderProcessSupervisor,
operation = this.operation,
): void {
this.#pending.set(root, { owner, operation });
this.#pending.set(root, {
owner,
operation:
this.#pending.get(root)?.operation ?? this.#artifacts.operation,
});
}
get pendingPaths(): readonly string[] {
@@ -251,7 +266,7 @@ export class ArtifactAnalysisResources {
async #closeResources(): Promise<void> {
let descriptorFailure: AnalysisError | undefined;
try {
await this.#artifacts.close();
await this.#artifacts.scope.close();
} catch (cause: unknown) {
descriptorFailure = this.#artifactFailure(cause);
}
@@ -262,14 +277,17 @@ export class ArtifactAnalysisResources {
throw analysisErrorWithCleanupFailure(
descriptorFailure,
cause,
this.operation,
this.#artifacts.operation,
);
throw cause;
}
if (descriptorFailure !== undefined) throw descriptorFailure;
}
#artifactFailure(cause: unknown, operation = this.operation): AnalysisError {
#artifactFailure(
cause: unknown,
operation = this.#artifacts.operation,
): AnalysisError {
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return this.cleanupFailure(cause.cleanup, cause, undefined, operation);
-35
View File
@@ -1,35 +0,0 @@
import { afterEach, expect, it, vi } from "vitest";
import { ProviderStartupDeadline } from "./ProviderDeadline.js";
afterEach(() => {
vi.restoreAllMocks();
});
it("keeps remaining time and cancellation classification stable across wall-clock jumps", () => {
const dateNow = vi.spyOn(Date, "now").mockReturnValue(10_000);
const caller = new AbortController();
const deadline = new ProviderStartupDeadline(10_000, caller.signal);
try {
dateNow.mockReturnValue(9_000_000_000_000);
const remaining = deadline.remainingMs();
expect(remaining).toBeGreaterThan(0);
expect(remaining).toBeLessThanOrEqual(10_000);
expect(Number.isInteger(remaining)).toBe(true);
expect(deadline.interruption).toBeUndefined();
caller.abort(new Error("caller stopped startup"));
expect(deadline.interruption).toBe("cancelled");
} finally {
deadline.dispose();
}
});
it("aborts a bounded wait when its real monotonic deadline expires", async () => {
const deadline = new ProviderStartupDeadline(40);
try {
await expect(deadline.wait(500)).resolves.toBe("aborted");
expect(deadline.interruption).toBe("timeout");
expect(deadline.remainingMs()).toBe(0);
} finally {
deadline.dispose();
}
});
+4 -4
View File
@@ -42,11 +42,11 @@ export class ProviderStartupDeadline {
) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
throw new RangeError("Provider startup timeout must be positive");
this.#deadlineAt = performance.now() + timeoutMs;
this.#deadlineAt = Date.now() + timeoutMs;
this.#externalSignal = signal;
this.#onExternalAbort = () => {
if (this.#controller.signal.aborted) return;
if (performance.now() >= this.#deadlineAt) {
if (Date.now() >= this.#deadlineAt) {
this.#interruption = "timeout";
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
@@ -79,13 +79,13 @@ export class ProviderStartupDeadline {
get interruption(): "cancelled" | "timeout" | undefined {
return (
this.#interruption ??
(performance.now() >= this.#deadlineAt ? "timeout" : undefined)
(Date.now() >= this.#deadlineAt ? "timeout" : undefined)
);
}
/** Milliseconds still available to the next startup phase. */
remainingMs(): number {
return Math.max(0, Math.ceil(this.#deadlineAt - performance.now()));
return Math.max(0, this.#deadlineAt - Date.now());
}
/** Wait for at most one polling interval under the shared deadline signal. */
@@ -1,3 +0,0 @@
/** Keep wall-clock timestamps separate from capture-relative elapsed time. */
export const monotonicProcessCaptureClock = (): number =>
Math.floor(performance.now());
+1 -5
View File
@@ -13,7 +13,6 @@ import type {
ProcessCaptureEventJournalEntry,
RecordProcessCaptureEvent,
} from "../../domain/process/processCapture.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
/** Mutable observation-order ledger whose writer is shared by capture producers. */
export interface ProcessCaptureJournal {
readonly entries: readonly ProcessCaptureEventJournalEntry[];
@@ -56,10 +55,7 @@ export const scheduleScenarioInteractions = (
const timer = scheduleProcessDelay(event.at_ms, () => {
options.dispatchedEventIndexes.add(eventIndex);
const terminal = getTerminal();
const dispatchedAt = Math.max(
0,
monotonicProcessCaptureClock() - started,
);
const dispatchedAt = Math.max(0, Date.now() - started);
let outcome: InteractionEvent["outcome"] = "dispatched";
if (terminal === undefined) outcome = "target_exited";
else {
@@ -5,7 +5,6 @@ import { parseProcessScenario } from "../../domain/process/processScenario.js";
import type { ProcessCaptureFinalization } from "../../domain/process/processCapture.js";
import { awaitTerminalExit } from "./ProcessCaptureLifecycle.js";
import type { ProcessTimer } from "./ProcessTimer.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
type Delivery = ProcessCaptureFinalization["signals"][number]["delivery"];
@@ -80,8 +79,8 @@ const start = (
idle_timeout_ms: 10_000,
...scenario,
}),
started: monotonicProcessCaptureClock(),
lastOutput: monotonicProcessCaptureClock,
started: Date.now(),
lastOutput: () => Date.now(),
signal,
signalTarget: fake.signalTarget,
recordFinalization: (snapshot) => {
+21 -53
View File
@@ -48,7 +48,6 @@ import {
type ProcessCaptureTruncationDetails,
} from "../../domain/process/processCaptureCoverage.js";
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
import type {
FilesystemCheckpoint,
@@ -267,10 +266,10 @@ export const settleProcessCaptureJournal = async (
quietMs = 25,
maxWaitMs = 500,
): Promise<void> => {
const deadline = monotonicProcessCaptureClock() + maxWaitMs;
const deadline = Date.now() + maxWaitMs;
let observed = journal.length;
let lastChangeAt = monotonicProcessCaptureClock();
while (monotonicProcessCaptureClock() < deadline) {
let lastChangeAt = Date.now();
while (Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 4));
// A stalled event loop can leave timer and poll callbacks that were already
// due queued behind this wake-up. Drain them before judging silence so a
@@ -278,8 +277,8 @@ export const settleProcessCaptureJournal = async (
await setImmediate();
if (journal.length !== observed) {
observed = journal.length;
lastChangeAt = monotonicProcessCaptureClock();
} else if (monotonicProcessCaptureClock() - lastChangeAt >= quietMs) return;
lastChangeAt = Date.now();
} else if (Date.now() - lastChangeAt >= quietMs) return;
}
};
@@ -338,12 +337,6 @@ export const buildCaptureResult = (
truncation_details: options.truncationDetails,
limitations: [
"The executable digest is a prelaunch file sample; matching path metadata immediately after spawn does not prove an atomic operating-system image binding.",
...(Date.parse(options.manifest.completed_at) <
Date.parse(options.manifest.started_at)
? [
"Wall-clock completion time precedes start time; elapsed capture timing is recorded separately and remains monotonic.",
]
: []),
"Process trees are sampled and may omit short-lived descendants.",
...(options.samplingPartial
? ["Process-tree sampling ended with an incomplete observation."]
@@ -667,7 +660,7 @@ export const observeSettlement = async (
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: 0 };
}
const started = monotonicProcessCaptureClock();
const started = Date.now();
let consecutiveEmpty = 0;
let sawLive = false;
let deadlineReached = false;
@@ -685,25 +678,19 @@ export const observeSettlement = async (
[...observations.values()].some(({ state }) => state === "unverifiable")
) {
recordEvent("lifecycle", 1);
return {
state: "unverifiable",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
return { state: "unverifiable", elapsed_ms: Date.now() - started };
}
if ([...observations.values()].every(({ state }) => state === "empty")) {
consecutiveEmpty += 1;
if (consecutiveEmpty >= 2) {
recordEvent("lifecycle", 1);
return {
state: "quiesced",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
return { state: "quiesced", elapsed_ms: Date.now() - started };
}
} else {
consecutiveEmpty = 0;
sawLive = true;
}
deadlineReached = monotonicProcessCaptureClock() - started >= settleMs;
deadlineReached = Date.now() - started >= settleMs;
if (deadlineReached) break;
await delay(50, undefined, { signal });
}
@@ -711,14 +698,8 @@ export const observeSettlement = async (
// A lone empty observation proves neither liveness nor quiescence; only an
// observed live member justifies alive_at_deadline.
return sawLive
? {
state: "alive_at_deadline",
elapsed_ms: monotonicProcessCaptureClock() - started,
}
: {
state: "unverifiable",
elapsed_ms: monotonicProcessCaptureClock() - started,
};
? { state: "alive_at_deadline", elapsed_ms: Date.now() - started }
: { state: "unverifiable", elapsed_ms: Date.now() - started };
};
/** Name why an attempt is unverified; a blank message never reaches the capture schema. */
@@ -805,10 +786,7 @@ export const awaitTerminalExit = async ({
if (finalizationStartedAt === undefined) return;
const record: (typeof finalizationSignals)[number] = {
signal: finalizationSignal,
sent_at_ms: Math.max(
0,
monotonicProcessCaptureClock() - finalizationStartedAt,
),
sent_at_ms: Math.round(performance.now() - finalizationStartedAt),
delivery: "unverified" as FinalizationDelivery,
reason: "delivery had not settled when the record was published",
};
@@ -878,7 +856,7 @@ export const awaitTerminalExit = async ({
terminal.kill("SIGKILL");
return;
}
finalizationStartedAt = monotonicProcessCaptureClock();
finalizationStartedAt = performance.now();
attempt("SIGTERM");
};
terminal.onExit((exit) => {
@@ -889,7 +867,7 @@ export const awaitTerminalExit = async ({
const finalizationElapsedMs =
finalizationStartedAt === undefined
? undefined
: Math.max(0, monotonicProcessCaptureClock() - finalizationStartedAt);
: Math.round(performance.now() - finalizationStartedAt);
recordEvent("lifecycle", 0);
for (const [eventIndex, event] of scenario.events.entries()) {
if (dispatchedEventIndexes.has(eventIndex)) continue;
@@ -897,10 +875,7 @@ export const awaitTerminalExit = async ({
interactions.push({
sequence,
scheduled_at_ms: event.at_ms,
dispatched_at_ms: Math.max(
0,
monotonicProcessCaptureClock() - started,
),
dispatched_at_ms: Math.max(0, Date.now() - started),
type: event.type,
data:
event.type === "input"
@@ -960,20 +935,14 @@ export const awaitTerminalExit = async ({
forceKill();
} else if (finalizationStartedAt !== undefined) {
if (
monotonicProcessCaptureClock() - finalizationStartedAt >=
performance.now() - finalizationStartedAt >=
scenario.finalization_ms
)
forceKill();
} else if (
monotonicProcessCaptureClock() - started >=
scenario.timeout_ms
) {
} else if (Date.now() - started >= scenario.timeout_ms) {
reason = "timeout";
terminateAtDeadline();
} else if (
monotonicProcessCaptureClock() - lastOutput() >=
scenario.idle_timeout_ms
) {
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
reason = "idle_timeout";
terminateAtDeadline();
}
@@ -1002,11 +971,10 @@ const PROCESS_CLEANUP_VERIFICATION_INTERVAL_MS = 25;
const verifyTokenOwnedProcessesUntilSettled = async (
verify: () => Promise<ProcessCleanupResult>,
): Promise<ProcessCleanupResult> => {
const deadline =
monotonicProcessCaptureClock() + PROCESS_CLEANUP_VERIFICATION_GRACE_MS;
const deadline = Date.now() + PROCESS_CLEANUP_VERIFICATION_GRACE_MS;
let result = await verify();
while (!result.cleaned) {
const remaining = deadline - monotonicProcessCaptureClock();
const remaining = deadline - Date.now();
if (remaining <= 0) return result;
await new Promise<void>((resolve) =>
setTimeout(
@@ -1320,7 +1288,7 @@ export const captureTerminalFrames = (options: {
}
outputBytes += bytes;
const atMs = normalizeProcessElapsedTime(
monotonicProcessCaptureClock() - options.started,
Date.now() - options.started,
options.scenario.normalization.time_bucket_ms,
);
const normalized = normalizeProcessText(
@@ -1,5 +1,4 @@
import type { ProcessCaptureCleanupReport } from "../../domain/process/processCapture.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
/**
* Progress port accepted by process capture.
@@ -62,7 +61,7 @@ const formatProgressMessage = (
/** Serialize observed capture status through one rate-limited reporter. */
export const createProcessCaptureProgressTracker = (
progress: ProcessCaptureProgress | undefined,
now: () => number = monotonicProcessCaptureClock,
now: () => number = Date.now,
) => {
const started = now();
let completed = 0;
+3 -4
View File
@@ -70,7 +70,6 @@ import {
observeProcessStartIdentity,
signalProcessWithStartIdentity,
} from "../ProcessOwnershipObservation.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
interface StartedCaptureRuntime {
readonly renderer: TerminalRenderer;
@@ -269,7 +268,7 @@ const startCaptureRuntime = async (
options.signal,
);
const startedAt = new Date();
const started = monotonicProcessCaptureClock();
const started = Date.now();
let lastOutput = started;
renderer = createTerminalRenderer(
scenario,
@@ -297,7 +296,7 @@ const startCaptureRuntime = async (
...options,
terminal,
started,
onOutput: () => (lastOutput = monotonicProcessCaptureClock()),
onOutput: () => (lastOutput = Date.now()),
renderer,
});
scheduleScenarioInteractions({
@@ -542,7 +541,7 @@ const completeCapture = async (options: {
},
{
name: "after_settlement",
at_ms: Math.max(0, monotonicProcessCaptureClock() - runtime.started),
at_ms: Math.max(0, Date.now() - runtime.started),
files: after.files,
effects: classifyFilesystemEffects(options.before, after),
truncated: after.truncated,
+1 -2
View File
@@ -6,7 +6,6 @@ import type {
} from "../../domain/process/processCapture.js";
import { execFileOutput } from "../ExecFileOutput.js";
import { readProcessRunId } from "../ProcessOwnership.js";
import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js";
const PROC_READ_CONCURRENCY = 64;
interface ProcessRow {
@@ -492,7 +491,7 @@ export const startProcessSampler = (options: {
}
return sampleProcesses({
rootPid,
elapsedMs: monotonicProcessCaptureClock() - started,
elapsedMs: Date.now() - started,
limit: limit + 1,
identities,
signal: controller.signal,
+3 -2
View File
@@ -54,7 +54,6 @@ import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import { registerApplicationTools } from "./registerApplicationTools.js";
import { registerArtifactTools } from "./registerArtifactTools.js";
import { registerNativeTools } from "./registerNativeTools.js";
import { registerBrowserScenarioTool } from "./registerBrowserScenarioTool.js";
import { registerBrowserTools } from "./registerBrowserTools.js";
import { registerWebScriptTool } from "./registerWebScriptTool.js";
@@ -108,6 +107,8 @@ import type { AdbDeviceAnalysisPort } from "../application/adb/AdbDeviceAnalysis
import { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
import { createAdbDeviceAnalysisProvider } from "../composition/adb.js";
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.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";
@@ -724,7 +725,7 @@ const registerBinaryAnalysisTools = ({
recordEvidence,
withAdmittedAnalysis,
};
registerNativeTools(server, { ...evidenceOptions, evidenceById });
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, evidenceOptions);
registerArtifactTools(server, { ...evidenceOptions, evidenceById });
registerManagedTools(server, { ...evidenceOptions, evidenceById });
if (session !== undefined)
+5 -13
View File
@@ -6,10 +6,7 @@ import {
artifactInspectionInputSchema,
} from "../contracts/artifactToolContracts.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import { summarizeRetainedAnalysis } from "../application/analysisView/AnalysisViewService.js";
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
import { ok } from "../domain/result.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
@@ -28,10 +25,6 @@ export const registerArtifactTools = (
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
},
): void => {
const retention = {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
};
registerEvidenceTools(server, ARTIFACT_TOOL_CONTRACTS, {
...options,
parametersForExecution: (operation, parameters) => {
@@ -44,13 +37,12 @@ export const registerArtifactTools = (
? { ...parameters, output_root: createArtifactExtractionDestination() }
: parameters;
},
preflight: (operation, parameters) =>
operation === "inspect_artifact" && parameters.detail === "summary"
? requireAnalysisViewRetention(operation, retention)
: ok(null),
projectEvidence: (operation, parameters, evidence) =>
operation === "inspect_artifact" && parameters.detail === "summary"
? summarizeRetainedAnalysis(evidence, retention)
? summarizeRetainedAnalysis(evidence, {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
})
: ok(evidence),
sourceEvidence: (operation, result) =>
operation === "inspect_artifact"
+1 -19
View File
@@ -33,16 +33,6 @@ interface EvidenceToolRegistration {
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Readonly<Record<string, JsonValue>>;
/** Exclude adapter-only selections, such as delivery detail, from Evidence identity. */
readonly parametersForEvidence?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Readonly<Record<string, JsonValue>>;
/** Refuse an unsatisfiable delivery selection before any analysis runs. */
readonly preflight?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
) => Result<unknown, AnalysisError>;
readonly projectEvidence?: (
operation: Exclude<AnalysisOperation, "health">,
parameters: Readonly<Record<string, JsonValue>>,
@@ -61,12 +51,6 @@ export const registerEvidenceTools = (
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
const ready = options.preflight?.(
contract.name,
jsonObjectSchema.parse(input),
);
if (ready !== undefined && !ready.ok)
return server.delivery.toCallToolResult(ready, contract);
const admitted = await options.withAdmittedAnalysis(
contract.name,
context.mcpReq.signal,
@@ -111,9 +95,7 @@ export const registerEvidenceTools = (
execution.value.provider,
{
operation: contract.name,
parameters:
options.parametersForEvidence?.(contract.name, parameters) ??
parameters,
parameters,
result: execution.value.result,
...(execution.value.analysisProfile === undefined
? {}
-54
View File
@@ -1,54 +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 { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok } from "../domain/result.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { Logger } from "pino";
import { registerEvidenceTools } from "./registerEvidenceTools.js";
/** Delivery detail selects a response shape; it never reaches the tools or Evidence identity. */
const withoutDelivery = (
operation: string,
parameters: Readonly<Record<string, JsonValue>>,
): Readonly<Record<string, JsonValue>> => {
if (operation !== "inspect_macho") return parameters;
const { detail: _detail, ...selected } = parameters;
return selected;
};
/** Register macOS native contracts; Mach-O inspection can deliver a retained summary. */
export const registerNativeTools = (
server: EvidenceMcpServer,
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
readonly evidenceById?: EvidenceLookup | undefined;
readonly withAdmittedAnalysis: import("./analysisAdmission.js").WithAdmittedAnalysis;
},
): void => {
const retention = {
recordEvidence: options.recordEvidence,
evidenceById: options.evidenceById,
};
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, {
...options,
parametersForExecution: withoutDelivery,
parametersForEvidence: withoutDelivery,
preflight: (operation, parameters) =>
operation === "inspect_macho" && parameters.detail === "summary"
? requireAnalysisViewRetention(operation, retention)
: ok(null),
projectEvidence: (operation, parameters, evidence) =>
operation === "inspect_macho" && parameters.detail === "summary"
? summarizeRetainedAnalysis(evidence, retention)
: ok(evidence),
});
};
+2 -2
View File
@@ -173,7 +173,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
];
phase = "workspace";
root = await this.createRuntime();
this.#resources.retain(root, undefined, operation);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "recording");
const execute = async (args: readonly string[]) => {
const output = await runOwnedCommand(
@@ -371,7 +371,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#resources.retain(root, cause.cleanupOwner, operation);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
+37 -55
View File
@@ -26,26 +26,6 @@ class FixtureProcess extends EventEmitter implements ProviderProcessHandle {
}
}
const fixtureLauncher =
(process: FixtureProcess): JadxLauncher =>
async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
it("joins pending input errors before detaching the owned protocol stream", async () => {
let completeWrite: ((cause: Error) => void) | undefined;
const failure = new Error("owned pipe closed during cancellation");
@@ -90,9 +70,26 @@ it("joins pending input errors before detaching the owned protocol stream", asyn
it("decodes split UTF-8 and newline bytes, then routes multiple complete frames", async () => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
fixtureLauncher(process),
launcher,
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -101,9 +98,7 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
const first = {
jsonrpc: "2.0",
id: 1,
result: {
content: [{ type: "text", text: "snow 雪 🦊 and literal �" }],
},
result: { content: [{ type: "text", text: "snow 雪 🦊" }] },
} satisfies JSONRPCMessage;
const second = {
jsonrpc: "2.0",
@@ -125,41 +120,28 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
await transport.close();
});
it.each([
["invalid UTF-8 byte", Buffer.from([0xff])],
["truncated UTF-8 sequence", Buffer.from([0xe2, 0x82])],
])("rejects %s in a complete JSON-RPC frame", async (_label, invalid) => {
const process = new FixtureProcess();
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
const errors: Error[] = [];
transport.onmessage = (message) => received.push(message);
transport.onerror = (cause) => errors.push(cause);
await transport.start();
process.stdout.write(
Buffer.concat([
Buffer.from('{"jsonrpc":"2.0","id":1,"result":{"text":"'),
invalid,
Buffer.from('"}}\n'),
]),
);
await new Promise<void>((resolve) => setImmediate(resolve));
await transport.close();
expect(received).toEqual([]);
expect(errors).toHaveLength(1);
expect(errors[0]?.message).toMatch(/encoded data was not valid/i);
});
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
fixtureLauncher(process),
launcher,
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -35,7 +35,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-capture-descriptor-");
@@ -67,12 +75,17 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_packet_fields"
: "inspect_packet_capture";
cleanup.path =
member === "capture"
resource === "capture"
? path
: member === "tool"
: resource === "tool"
? command
: member === "limiter"
: resource === "limiter"
? limiter
: "/proc/self/limits";
cleanup.denied = true;
@@ -84,24 +97,55 @@ it
cleanup.path = "";
});
const service = new PacketCaptureService(provider);
const first = await service.inspect({ path, fields: ["frame.number"] });
const first = discovery
? await service.inspectFields({ query: "usb" })
: await service.inspect({ path, fields: ["frame.number"] });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
error: {
cleanupIncomplete: true,
cleanupResources: [cleanup.path],
operation,
},
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const launchCount = launches;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
let closingOperation = operation;
if (discovery) {
cleanup.denied = false;
const recovered = await service.inspect({
path,
fields: ["frame.number"],
});
expect(recovered.ok).toBe(true);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
expect(launches).toBeGreaterThan(launchCount);
cleanup.denied = true;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation: "inspect_packet_capture" },
});
expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0);
closingOperation = "inspect_packet_capture";
}
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation: closingOperation,
});
cleanup.denied = false;
await provider.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
},
);
@@ -11,6 +11,9 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createDeferred } from "../../fixtures/binarySession.js";
import { Cli } from "incur";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { silentLogger } from "../../../src/logger.js";
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
const fixture = async (mode = "ok", failCleanup = false) => {
@@ -625,3 +628,34 @@ it("retains completed discovery on late cancellation and cleanup failure", async
await f.service.close();
}
});
it("preserves discovery resource ownership through CLI shutdown retries", async () => {
const f = await fixture("cleanup", true);
const cli = Cli.create("discovery-cleanup", { sync: false });
registerCaptureCommands(cli, silentLogger, {}, f.service);
let stdout = "";
try {
await cli.serve(
["inspect-packet-fields", "--query", "usb", "--format", "json"],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
cleanup_error: {
details: { operation: "inspect_packet_fields" },
},
},
},
});
} finally {
f.allowCleanup();
await f.service.close();
}
});
@@ -191,9 +191,12 @@ describe.skipIf(process.platform === "win32")(
it.each([
["name=other\nversion=12.1.3\n", "does not match"],
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
["name=ghidra-allegrex\nversion=12.1.\\uZZZZ\n", "Unicode escape"],
[
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
"exactly one version",
],
])(
"rejects mismatched or malformed extension metadata %s",
"rejects incompatible or ambiguous extension metadata %s",
async (properties, reason) => {
const { root } = await installation();
await writeFile(join(root, "extension.properties"), properties);
@@ -501,38 +504,3 @@ describe.skipIf(process.platform === "win32")(
});
},
);
describe.skipIf(process.platform === "win32")(
"PSP extension property syntax",
() => {
it.each([
{
form: "escaped key and value with colon separator",
properties: "n\\u0061me : ghidra-allegrex\nver\\u0073ion=12.1.3\n",
},
{
form: "continued key and value lines",
properties: "name=ghidra-\\\n allegrex\nversion=12.1.\\\n 3\n",
},
{
form: "duplicate keys use the last value",
properties:
"name=wrong\nname=ghidra-allegrex\nversion=12.1.4\nversion=12.1.3\n",
},
])(
"accepts Java Properties $form and hashes raw bytes",
async ({ properties }) => {
const { root } = await installation();
const canonical = await inspectGhidraPspExtension(root, "12.1.3");
const latin1Properties = Buffer.from(
`${properties}author=caf\u00e9\n`,
"latin1",
);
await writeFile(join(root, "extension.properties"), latin1Properties);
const extension = await inspectGhidraPspExtension(root, "12.1.3");
expect(extension.id).toBe("ghidra-allegrex");
expect(extension.sha256).not.toBe(canonical.sha256);
},
);
},
);
@@ -10,8 +10,6 @@ const injectedFilesystemFailures = vi.hoisted(() => ({
closeNext: false,
blockCloseRetries: false,
chmodNext: false,
syncAbortAfter: undefined as AbortController | undefined,
syncCount: 0,
rootIdentityPath: undefined as string | undefined,
}));
@@ -46,15 +44,6 @@ vi.mock("node:fs/promises", async (importOriginal) => {
await close();
};
}
if (injectedFilesystemFailures.syncAbortAfter !== undefined) {
const sync = handle.sync.bind(handle);
handle.sync = async () => {
await sync();
injectedFilesystemFailures.syncCount += 1;
if (injectedFilesystemFailures.syncCount === 2)
injectedFilesystemFailures.syncAbortAfter?.abort();
};
}
return handle;
},
};
@@ -93,34 +82,6 @@ describe("safe artifact output close failures", () => {
},
);
it.skipIf(process.platform === "win32")(
"keeps the tree unpublished when cancellation arrives during commit durability",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-cancel-");
const output = join(parent, "unpublished");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("pending output");
await tree.write("file.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
const controller = new AbortController();
injectedFilesystemFailures.syncCount = 0;
injectedFilesystemFailures.syncAbortAfter = controller;
try {
await expect(tree.commit(controller.signal)).rejects.toMatchObject({
reason: "cancelled",
});
expect(tree.published).toBe(false);
} finally {
injectedFilesystemFailures.syncAbortAfter = undefined;
injectedFilesystemFailures.syncCount = 0;
}
expect(await tree.rollback()).toMatchObject({ status: "complete" });
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.skipIf(process.platform === "win32")(
"preserves setup failure when closing the staging handle also fails",
async () => {
@@ -1,216 +0,0 @@
import { silentLogger } from "../../../src/logger.js";
import { copyFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
import { createServer } from "../../../src/server/createServer.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { ok } from "../../../src/domain/result.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const evidenceOf = <Schema extends z.ZodType>(schema: Schema) =>
z.object({
evidence_id: z.string(),
parameters: z.record(z.string(), z.unknown()),
normalized_result: schema,
});
const countSchema = z.object({
returned: z.number(),
total: z.number().nullable(),
exhaustive: z.boolean(),
});
const summarySchema = z.object({
kind: z.literal("summary"),
parent_evidence_id: z.string(),
summary: z.object({
uuid: z.string().nullable(),
collections: z.record(z.string(), countSchema),
provenance_count: z.number(),
}),
});
const pageSchema = z.object({
kind: z.literal("macho"),
item: z.array(z.unknown()),
coverage: z.object({ next_offset: z.number().nullable() }),
});
describe.skipIf(process.platform !== "darwin")(
"Mach-O summary delivery through MCP",
() => {
mcpTest(
"retains complete inspect_macho Evidence and pages its exact rows",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-macho-summary-mcp-"),
"ls",
);
await copyFile("/bin/ls", target);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const complete = await client.callTool({
name: "inspect_macho",
arguments: {},
});
expect(complete.isError, JSON.stringify(complete.content)).not.toBe(
true,
);
const full = evidenceOf(inspectMachoSchema).parse(
complete.structuredContent,
);
// Omitted detail keeps the default Evidence parameters unchanged.
expect(full.parameters).toEqual({});
const summarized = await client.callTool({
name: "inspect_macho",
arguments: { detail: "summary" },
});
expect(summarized.isError, JSON.stringify(summarized.content)).not.toBe(
true,
);
const summary = evidenceOf(summarySchema).parse(
summarized.structuredContent,
).normalized_result;
// Delivery detail never reaches the tools or the source Evidence ID.
expect(summary.parent_evidence_id).toBe(full.evidence_id);
const report = full.normalized_result;
expect(summary.summary.uuid).toBe(report.uuid);
expect(summary.summary.provenance_count).toBe(report.provenance.length);
for (const name of ["imports", "exports", "dependencies"] as const)
expect(summary.summary.collections[name]).toEqual({
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
});
expect(JSON.stringify(summarized.structuredContent)).not.toContain(
report.imports.items[0]?.name ?? "_",
);
// Every facet must reassemble the unparsed complete rows exactly.
const raw = z
.object({ normalized_result: z.record(z.string(), z.unknown()) })
.parse(complete.structuredContent).normalized_result;
const facets = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
"provenance",
] as const;
for (const facet of facets) {
const rows: unknown[] = [];
let offset: number | null = 0;
while (offset !== null) {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "macho", facet, offset, limit: 16 },
},
});
expect(paged.isError, JSON.stringify(paged.content)).not.toBe(true);
const page = evidenceOf(pageSchema).parse(
paged.structuredContent,
).normalized_result;
rows.push(...page.item);
offset = page.coverage.next_offset;
}
expect(rows, facet).toEqual(
facet === "provenance"
? raw.provenance
: z.object({ items: z.array(z.unknown()) }).parse(raw[facet])
.items,
);
}
const wrongKind = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "wasm", facet: "exports" },
},
});
expect(wrongKind.isError).toBe(true);
expect(JSON.stringify(wrongKind.content)).toContain(
"Mach-O inspection supports summary and macho views.",
);
},
);
},
);
mcpTest(
"refuses summary delivery before analysis when the server retains no Evidence",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-summary-preflight-"),
"tool",
);
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const executed: string[] = [];
const session = createTestBinarySession(() => ({
execute: (operation) => {
executed.push(operation);
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(ok(null)),
}));
onTestFinished(async () => {
await session.close();
});
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
const client = await mcp.connect(
createServer({ kind: "fixed", analysis: session }),
);
const refused = [];
for (const name of ["inspect_macho", "inspect_artifact"])
refused.push(
await client.callTool({ name, arguments: { detail: "summary" } }),
);
// Neither analysis ran only to be discarded by the delivery refusal.
expect(executed.filter((operation) => operation !== "health")).toEqual([]);
for (const result of refused)
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
},
);
@@ -4,7 +4,7 @@ import { access, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, vi } from "vitest";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
@@ -123,93 +123,6 @@ const terminateFixtureProcess = async (pid: number): Promise<void> => {
await waitForProcessExit(pid);
};
itWithCaptureCapability(
"keeps the process deadline bounded when the wall clock moves backward",
async () => {
const wallStart = Date.now();
let wallReads = 0;
const now = vi.spyOn(Date, "now").mockImplementation(() => {
wallReads += 1;
return wallReads === 1 ? wallStart : wallStart - 60_000 + wallReads;
});
const controller = new AbortController();
const fallback = setTimeout(() => controller.abort(), 1_500);
try {
const result = await captureProcessScenario(
parseProcessScenario({
executable: process.execPath,
arguments: [processFixture, "hang"],
working_directory: dirname(processFixture),
timeout_ms: 100,
idle_timeout_ms: 5_000,
}),
controller.signal,
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.exit.reason).toBe("timeout");
} finally {
clearTimeout(fallback);
now.mockRestore();
}
},
10_000,
);
itWithCaptureCapability(
"preserves reversed wall-clock observations and monotonic frames across capture",
async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-01-02T00:00:00.000Z"));
try {
const result = await captureProcessScenario(
parseProcessScenario({
executable: process.execPath,
arguments: [processFixture, "partial"],
working_directory: dirname(processFixture),
settle_ms: 0,
timeout_ms: 5_000,
idle_timeout_ms: 5_000,
}),
undefined,
process.platform,
process.env,
undefined,
undefined,
{
async report(update) {
if (update.phase === "running")
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
},
},
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.frames.length).toBeGreaterThan(0);
expect(Date.parse(result.value.manifest.completed_at)).toBeLessThan(
Date.parse(result.value.manifest.started_at),
);
expect(result.value.limitations).toContain(
"Wall-clock completion time precedes start time; elapsed capture timing is recorded separately and remains monotonic.",
);
expect(
result.value.frames.map(({ at_ms }) => at_ms),
"capture-relative frame times stay ordered and nonnegative",
).toEqual(
[...result.value.frames.map(({ at_ms }) => at_ms)].sort(
(left, right) => left - right,
),
);
expect(result.value.frames.every(({ at_ms }) => at_ms >= 0)).toBe(true);
expect(result.value.exit.reason).toBe("exited");
expect(result.value.settlement.elapsed_ms).toBeGreaterThan(0);
} finally {
vi.useRealTimers();
}
},
10_000,
);
itWithCaptureCapability(
"cleans detached run-token children omitted by sampling and preserves an unowned neighbor",
async () => {
@@ -3,7 +3,7 @@ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage, createPackageWithOptions } from "@electron/asar";
import { expect, it, vi } from "vitest";
import { expect, it } from "vitest";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
@@ -13,7 +13,6 @@ import {
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { DirectoryArtifactReader } from "../../../../src/artifacts/DirectoryArtifactReader.js";
it.each(["file", "directory"] as const)(
"rolls back when an inventoried %s disappears before extraction",
@@ -62,42 +61,6 @@ it("still refuses a regular file added after inventory and rolls back", async ()
await expect(access(output)).rejects.toThrow();
});
it("rolls back when cancellation arrives while closing the materialization reader", async () => {
const root = await createTestTempDirectory("rea-extract-cancel-close-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "payload.txt"), "complete payload\n");
const snapshot = await scanArtifactInventory(source);
const output = join(root, "output");
const controller = new AbortController();
const close = DirectoryArtifactReader.prototype.close;
const closeSpy = vi
.spyOn(DirectoryArtifactReader.prototype, "close")
.mockImplementation(async function (this: DirectoryArtifactReader) {
controller.abort();
await close.call(this);
});
try {
await expect(
materializeArtifactInventory(
{
inputPath: source,
inputFormat: "asar",
outputRoot: output,
environment: process.env,
integrityPolicy: "fail",
},
source,
snapshot,
controller.signal,
),
).rejects.toMatchObject({ reason: "cancelled" });
await expect(access(output)).rejects.toThrow();
} finally {
closeSpy.mockRestore();
}
});
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");
@@ -3,8 +3,6 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it, onTestFinished } from "vitest";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
@@ -22,26 +20,6 @@ const fatSlices = async (
};
describe("Mach-O slice reader with system lipo", () => {
it("names the process ownership helper prerequisite when lipo cannot be supervised", async () => {
const prerequisite =
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.";
const reader = new MachOSliceArtifactReader(
process.execPath,
{},
new XcrunCommandRunner({}, undefined, () =>
Promise.reject(new DarwinProcessOwnershipInspectionError(prerequisite)),
),
);
onTestFinished(() => reader.close());
const enumerate = async () => {
for await (const _entry of reader.entries()) continue;
};
await expect(enumerate()).rejects.toMatchObject({
reason: "unavailable",
message: `lipo could not enumerate universal Mach-O slices: ${prerequisite}`,
});
});
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls slice ranges against its FAT table",
async () => {
@@ -8,7 +8,6 @@ import {
type NativeCommandLauncher,
} from "../../../../src/native/CommandRunner.js";
import { ok } from "../../../../src/domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
afterEach(() => vi.unstubAllEnvs());
@@ -211,23 +210,3 @@ it.skipIf(process.platform === "win32")(
if (!killed.ok) expect(killed.error.reason).toBe("nonzero-exit");
},
);
it("keeps the ownership helper prerequisite when xcrun cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
);
const runner = new XcrunCommandRunner({}, undefined, () =>
Promise.reject(inspection),
);
const result = await runner.run("file", [], {});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
tool: "file",
reason: "io",
detail: inspection.message,
cause: { tool: "xcrun", detail: inspection.message, cause: inspection },
});
});
@@ -1,5 +1,4 @@
import { createHash } from "node:crypto";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
import { EventEmitter } from "node:events";
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -281,30 +280,6 @@ describe("native command failure capture and limits", () => {
stderr_bytes: expect.any(Number),
},
});
expect(projectAnalysisError(result.error).details).not.toHaveProperty(
"diagnostics.detail",
);
});
it("projects the ownership helper prerequisite when a command cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.",
);
const runner = new XcrunCommandRunner(
{},
() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
() => Promise.reject(inspection),
);
const result = await new NativeMacOSProvider({}, runner, "darwin")
.createClient(machoTarget("/private/fixture"))
.execute("demangle_swift", { symbols: ["fixture-symbol"] });
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: { reason: "io", detail: inspection.message },
});
});
it("retains output written before cancellation and reaps the stalled command", async () => {
@@ -35,7 +35,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-signal-descriptor-");
@@ -67,12 +75,17 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_signal_decoders"
: "decode_signal_recording";
cleanup.path =
member === "capture"
resource === "capture"
? path
: member === "tool"
: resource === "tool"
? command
: member === "limiter"
: resource === "limiter"
? limiter
: "/proc/self/limits";
cleanup.denied = true;
@@ -84,22 +97,29 @@ it
cleanup.path = "";
});
const service = new SignalRecordingService(provider);
const first = await service.decode({ path, decoders: "uart" });
const first = discovery
? await service.inspectDecoders({ query: "uart" })
: await service.decode({ path, decoders: "uart" });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
error: {
cleanupIncomplete: true,
cleanupResources: [cleanup.path],
operation,
},
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const launchCount = launches;
expect(await service.decode({ path, decoders: "uart" })).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation,
});
cleanup.denied = false;
await provider.close();